stratis
stratis

Reputation: 8052

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 '[email protected]'
    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.

Upvotes: 1

Views: 1309

Answers (1)

Ngoral
Ngoral

Reputation: 4824

You can use after :create block for it:

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

    after :create do |account|
      account.users << account.owner
    end
  end
end

Upvotes: 2

Related Questions