使用RSPEC和FactoryGirl测试Rails深层嵌套属性

时间:2013-10-02 23:14:14

标签: ruby-on-rails rspec factory-bot nested-attributes has-many-through

我需要一些帮助让我的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 个答案:

答案 0 :(得分:1)

几天后,我在阅读blog 1blog 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,也可以为此答案创建一个类似的块来处理它。