我需要一些帮助才能让我的factory_girl设置正确,其中有一个嵌套的属性。以下是三个参考模型。使用RSPEC和FactoryGirl测试Rails深嵌套属性
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
注意,位置是在人员记录下筑巢,但它需要经过两个模型要嵌套。我可以得到这样的测试:
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
我应该能够在一行中创建所有这三个记录,但还没有弄清楚如何处理。这是我想正确的有工作的结构:
factory :person do
...
trait :location_1 do
person_locations_attributes { location_attributes { FactoryGirl.attributes_for(:location, :location_1) } }
end
end
我有其他车型,其能够通过类似的语法来创建的,但它只有一个嵌套的属性与此更深的嵌套。
如上进入,我得到以下错误:
FactoryGirl.create(:person, :location_1)
undefined method `location_attributes' for #<FactoryGirl::SyntaxRunner:0x007fd65102a380>
此外,我希望能够正确地测试我控制器设置为创建与嵌套位置的新用户。如果我不能把呼叫接到一条线路,那么做到这一点很困难。
感谢您的帮助!希望我在上面提供了足够的帮助,以便在创建与嵌套属性有很多直通关系时提供帮助。
另一个很好的资源是http://robots.thoughtbot.com/remove-duplication-with-factorygirls-traits – AKWF