http://www.rubydoc.info/gems/factory_girl/file/GETTING_STARTED.md#Associations を見ると、
belongs_to
は association
メソッドでデータを作っているけど、 has_many
は after_create
で
データを作っている。
association
メソッドの場合 FactoryGirl.create(:post, author: author)
とすれば別のものを
指定することも出来るが、 has_many
なデータについては必ず after_create
で作られてしまっていて変更する手段がない。
これがテスト書くときに割とうざいことが多い。
で、色々試した結果、次のやり方でうまくいった。
FactoryGirl.define do
factory :post do
title "Through the Looking Glass"
user
end
factory :user do
name "John Doe"
factory :user_with_posts do
transient do
# build(:post) だと余分な user が作られてしまうため user: nil を指定する
posts { [build(:post, user: nil)] }
end
after(:create) do |user, evaluator|
user.posts = evaluator.posts
end
end
end
end
# rspec
FactoryGirl.create(:user_with_posts, posts: [FactoryGirl.create(:post), FactoryGirl.create(:post)])
追記
同僚からの指摘によりすっきりした書き方が出来るようになりました。