Reputation: 731
I have a User
that has_many
posts in Rails 4.1.6. Following the Getting Started page for Factory Girl, I have created these factories:
factory :post do
skip_create
title 'foo bar'
user
end
factory :user do
skip_create
id 1
username 'alice'
factory :user_with_posts do
skip_create
transient do
posts_count 5
end
after(:build) do |user, evaluator|
build_list(:post, evaluator.posts_count, user: user)
end
end
end
But calling build(:user_with_posts)
returns a User
with an empty posts
array. Calling build_list(:post, 5, user: user)
(with a pre-built User
) works.
What am I missing?
Also, is there a way to set a global skip_create
so I don't have to set it on each factory?
Upvotes: 1
Views: 74
Reputation: 882
I had a similar problem, and all according to all the docs I was reading, it should have been working. Here is what finally worked (adapted for your code):
change
build_list(:post, evaluator.posts_count, user: user)
to
user.posts = build_list(:post, evaluator.posts_count, user: user)
Let me know if that doesn't work, but that's what solved it for me.
Upvotes: 1