Hommer Smith
Hommer Smith

Reputation: 27852

Add (has_many) association to FactoryGirl.create?

I know how to create a has_many associations when defining a Factory:

factory :user do
    name "John Doe"
    factory :user_with_posts do
      ignore do
        posts_count 5
      end

      after(:create) do |user, evaluator|
        create_list(:post, evaluator.posts_count, user: user)
      end
    end
  end

But how would I do that when I am actually creating the Factory, such as:

Factory.create(:user, :posts << ??)

Upvotes: 1

Views: 59

Answers (1)

ivalkeen
ivalkeen

Reputation: 1411

One way is to use a block like this:

FactoryGirl.create(:user) do |user|
  FactoryGirl.create_list(:post, 10, user: user)
end

Upvotes: 1

Related Questions