Mirror318
Mirror318

Reputation: 12663

FactoryGirl—Add a has_many record to a factory

With FactoryGirl I know I can make singular attributes like this:

FactoryGirl.define do
  factory :company do
    trading_name { FFaker::Company.name }
    legal_type { legal_types.keys.sample }
    updated_by { FactoryGirl.create(:user) }
    ...

Now I'm trying to add a user, but not sure how to do it.

I tried:

users { FactoryGirl.create(:user) }

But got an error on an each loop because users wasn't the collection of users, it was changed to be that single user.

So how do you create has_many objects in a factory? How do you make sure they are linked to each other? Some people do an after(:create) but I'd like to make the users before saving the Company record.

Upvotes: 0

Views: 76

Answers (1)

Ilya Lavrov
Ilya Lavrov

Reputation: 2860

Association section of Factory Girl documentation says to use after(:create). In your case code will be:

FactoryGirl.define do
  factory :company do
    ...

    after(:create) do |company|
      create_list(:user, 3, company: company)
    end

Update: In a case you have after_save validation in User model you may use after(:build) hook instead of after(:create):

    after(:build) do |company|
      company.users << build(:user)
    end

Upvotes: 1

Related Questions