LoginSignup
14
12

More than 5 years have passed since last update.

FactoryGril の after_create で has_many 関連のデータを作るときの冴えたやり方

Last updated at Posted at 2015-02-25

http://www.rubydoc.info/gems/factory_girl/file/GETTING_STARTED.md#Associations を見ると、
belongs_toassociation メソッドでデータを作っているけど、 has_manyafter_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)])

追記

同僚からの指摘によりすっきりした書き方が出来るようになりました。

14
12
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
12