RSpec error User must exist with FactoryGirl
Asked Answered
M

2

7

I'm creating some test to test a controller and model. When I use FactoryGirl to create fake data I'm getting errors that the User (which the record belongs to) does not exist.

Here is my model composition.rb

class Composition < ActiveRecord::Base
  belongs_to :user
  belongs_to :group

  validates :name, presence: true, uniqueness: {scope: :user_id}

end

Here is my FactoryGirl file composition.rb

require 'faker'

FactoryGirl.define do
  factory :composition do
    name { Faker::Name.name }
    description { Faker::Lorem.words }
    import_composition { Faker::Boolean.boolean }
    import_composition_file { Faker::File.file_name('path/to') }
  end
end

This is my the RSpec test that I have until this far

require 'rails_helper'

  describe CompositionsController do

    before(:each) do
       @user = FactoryGirl.create(:user)
       @group = FactoryGirl.create(:group)
       sign_in @user
       @composition = Composition.new(FactoryGirl.create(:composition), user_id: @user.id, group_id: @group.id)
    end

  describe "GET #index" do
    it "renders the index template" do
      get :index

      expect(assigns(:composition).to eq(@composition))
      expect(response).to render_template("index")
    end
  end

end

Right now I'm getting an error: Validation failed: User must exist, Group must exist

When I don't user FactoryGirl to create a record everything works fine.

Does any body have an suggestion why it's failing?

Microsurgery answered 14/2, 2017 at 9:16 Comment(1)
@composition = FactoryGirl.create(:composition, user_id: @user.id, group_id: @group.id)Cunctation
P
2

You don't need to pass FactoryGirl as a param to Model

@composition = FactoryGirl.create(:composition, user: @user, group: @group)

If you don't want to create the record but just want it to initialize, use build instead of create

@composition = FactoryGirl.build(:composition, user: @user, group: @group)
Pederasty answered 14/2, 2017 at 9:21 Comment(1)
Thanks! This fixed my issue. It's running now. All tests have passedMicrosurgery
P
0

something of your dependecies is breaking the model of user thats why user is not being created, you need to specify what is the primary_key again:

class User < ApplicationRecord
  self.primary_key = 'id'
end
Phosphorite answered 28/2, 2023 at 3:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.