factory_girl の設定を正しくするには、いくつかの助けが必要です。これには、ネストされた属性を持つ複数のものがあります。参考までに3機種を紹介します。
location.rb
class Location < ActiveRecord::Base
has_many :person_locations
has_many :people, through: :person_locations
end
person_location.rb
class PersonLocation < ActiveRecord::Base
belongs_to :person
belongs_to :location
accepts_nested_attributes_for :location, reject_if: :all_blank
end
person.rb
class Person < ActiveRecord::Base
has_many :person_locations
has_many :locations, through: :person_locations
accepts_nested_attributes_for :person_locations, reject_if: :all_blank
end
場所は person レコードの下にネストされていますが、ネストするには 2 つのモデルを通過する必要があることに注意してください。テストを次のように機能させることができます。
it "creates the objects and can be called via rails syntax" do
Location.all.count.should == 0
@person = FactoryGirl.create(:person)
@location = FactoryGirl.create(:location)
@person_location = FactoryGirl.create(:person_location, person: @person, location: @location)
@person.locations.count.should == 1
@location.people.count.should == 1
Location.all.count.should == 1
end
これら 3 つのレコードすべてを 1 行で作成できるはずですが、まだ方法がわかりません。正しく動作させたい構造は次のとおりです。
factory :person do
...
trait :location_1 do
person_locations_attributes { location_attributes { FactoryGirl.attributes_for(:location, :location_1) } }
end
end
同様の構文で作成できる他のモデルがありますが、このより深いネストに対して、ネストされた属性は 1 つしかありません。
上記のように、次のエラーが表示されます。
FactoryGirl.create(:person, :location_1)
undefined method `location_attributes' for #<FactoryGirl::SyntaxRunner:0x007fd65102a380>
さらに、ネストされた場所を持つ新しいユーザーを作成するためのコントローラーのセットアップを適切にテストできるようにしたいと考えています。コールを 1 行にまとめられない場合、これを行うのは困難です。
ご協力いただきありがとうございます!!うまくいけば、ネストされた属性との関係を介して多数を作成しているときに、他の人にも役立つように上記で十分に提供したことを願っています.