相互接続関連

オブジェクトが相互接続する方法は際限なくあり、factory_botは常にそうした関係を扱うのに向いていないかもしれません。 factory_botを使って個々のオブジェクトを構築し、素のRubyで補助メソッドを書いてこうしたオブジェクトを結び付けるのが理に適っている場合があります。

つまり、より複雑で相互接続された関係は、行内関連と構築されるinstanceへの参照とを使ってfactory_botで構築できるということです。

モデルが以下のようなものであるとします。 ここで紐付くStudentProfileは両方とも同じSchoolに属します。

class Student < ApplicationRecord
  belongs_to :school
  has_one :profile
end

class Profile < ApplicationRecord
  belongs_to :school
  belongs_to :student
end

class School < ApplicationRecord
  has_many :students
  has_many :profiles
end

生徒とプロファイルが相互に接続し、同じ学校にあることを以下のようなファクトリで確かめられます。

FactoryBot.define do
  factory :student do
    school
    profile { association :profile, student: instance, school: school }
  end

  factory :profile do
    school
    student { association :student, profile: instance, school: school }
  end

  factory :school
end

なおこの方法はbuildbuild_stubbedcreateで上手くいきます。 ただしattributes_forを使うと紐付けからnilが返ります。

また、独自のinitialize_with内で属性を代入したとき(例えばinitialize_with { new(**attributes) })、これらの属性はinstanceを参照すべきではないことにも注意してください。 nilになるからです。