lundi 15 mai 2017

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.

Aucun commentaire:

Enregistrer un commentaire