FactoryGirlでhas_many(またはbelongs_to)な入れ子構造データを定義する
あるマスターデータをDBに入れたいが、テスト時にもそのマスターデータは使いたいので、db/seed.rbを使わずFactoryGirlでデータを突っ込んでいる。その方法が果たして現時点でのベストプラクティスなのかはわからないが。 (その方法自体はこちらの記事参照:http://naoty.hatenablog.com/entry/20111030/1319973849)
何にしてもマスターデータを入れる場合、そのデータは複数のテーブルにまたがっててhas_manyな関係だったりするかもしれない。 そういうデータをFactoryGirlで扱う時のメモ。
こういう構造のマスターデータを入れたいとする。
class Author < ActiveRecord::Base has_many :books end class Book < ActiveRecord::Base belongs_to :author end
has_manyの場合
# spec/factories/authors.rb FactoryGirl.define factory :soseki, :class => Author do |author| author.name '夏目漱石' author.books {[ FactoryGirl.create(:neko) ]} end end
# spec/factories/books.rb FactoryGirl.define factory :neko, :class => Book do |book| book.name '吾輩は猫である' end end
belongs_toの場合
# spec/factories/authors.rb FactoryGirl.define factory :soseki, :class => Author do |author| author.name '夏目漱石' end end
# spec/factories/books.rb FactoryGirl.define factory :neko, :class => Book do |book| book.name '吾輩は猫である' association :author, factory: :soseki end end
ポイント
has_manyとかbelongs_toをモデルに予め書いておかないと、associationがforeign_keyを自動挿入してくれない。 あとbelongs_to :author, class_name: 'Author', foreign_key: 'author_name_id'みたいに外部キーを違うものにしてても、belongs_toさえちゃんと設定しておけばうまく自動挿入してくれる。