[英]Rails 4 Testing with RSpec and FactoryGirl, nested attributes not saving
[英]Testing Rails Deep Nested Attributes with RSPEC and FactoryGirl
我需要一些幫助來使我的factory_girl設置正確無誤,該設置具有許多嵌套屬性。 這是三個模型供參考。
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>
此外,我希望能夠正確測試我的控制器設置,以創建具有嵌套位置的新用戶。 如果我無法將電話打到一條線上,很難做到這一點。
謝謝你的幫助!! 希望我在上面提供了足夠的信息,以幫助其他人在創建具有嵌套屬性的具有完全關聯的關系時使用。
幾天后,在閱讀了博客1和博客2之后,我發現了這個問題。 現在正在重構我的所有FactoryGirl代碼。
FactoryGirl應該如下所示:
factory :person do
...
trait :location_1 do
after(:create) do |person, evaluator|
create(:person_location, :location_1, person: person)
end
end
end
person_location工廠應該很簡單,然后遵循上面的代碼。 您可以執行原始問題中的location_attributes或創建與此答案類似的塊以在那里處理它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.