Factory Girl で関連を定義する
1対1の関連を持つ users テーブルと profiles テーブルがあり、User モデルと Profile モデルがそれぞれ以下のように定義されているとします。
users テーブル
field | type | |
---|---|---|
id | int | プライマリキー |
name | string | |
string |
profiles テーブル
field | type | |
---|---|---|
id | int | プライマリキー |
user_id | int | 外部キー |
sex | string | |
age | int |
# app/models/user.rb class User < ActiveRecord::Base has_one :profile end
# app/models/profile.rb class Profile < ActiveRecord::Baser belongs_to :user end
User は一つの Profile を持ち、Profile は一人の User に紐付けられています。
これらの関連付けられたモデルに関するテストを書くぞってなったとき、User を create したら Profile も create されてほしいという場合があると思います。
そういったときには、Factory Girl で以下のように定義することで実現できます。
User の factory 名が user のとき
# spec/factories/user.rb require 'factory_girl' FactoryGirl.define do factory :user do name: 'test' email: 'test@example.com' after :create do |u| create(:profile, user: u) # create(:profile, user_id: u.id) と同義 u.reload end end
# spec/factories/profile.rb require 'factory_girl' FactoryGirl.define do factory :profile do user sex 'man' age 100 end end
User の factory 名が user 以外のとき
# spec/factories/user.rb require 'factory_girl' FactoryGirl.define do factory :admin_user, class: user do name: 'admin' email: 'test@example.com' after :create do |u| create(:profile, user: u) u.reload end end
# spec/factories/profile.rb require 'factory_girl' FactoryGirl.define do factory :profile do association :user, factory: :admin_user sex 'man' age 100 end end
association で明示することで関連付けられます。