mercredi 30 août 2017

Factory girl association self referencing the parent model

In my application an account can have a single owner (user) and multiple users.

In my tests I do this:

# account_factory_static.rb
FactoryGirl.define do
  factory :account do
    name 'demoaccount'
    association :owner, :factory => :user
  end
end

# user_factory_static.rb
FactoryGirl.define do
  factory :user do
    email 'demo@example.com'
    first_name 'Jon'
    last_name 'Doe'
    password 'password'
  end
end

and use them like below:

let(:account) { FactoryGirl.create(:account) }

The problem is that right nowaccount.users.count equals 0 because I have no way to do something like @account.users << @account.owner like I do in my controllers when a user signs up.

The question is how can I add the associated account's id to the account_id attribute of the user in FactoryGirl?

In other words how do you do it in FactoryGirl?

Thanks.

Aucun commentaire:

Enregistrer un commentaire