0

我需要一些帮助来正确设置我的 factory_girl 设置,其中包含嵌套属性。以下是三个模型供参考。

位置.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

人.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>

此外,我希望能够正确测试我的控制器设置,以创建具有嵌套位置的新用户。如果我不能把电话接到一条线上,这将很难做到。

谢谢你的帮助!!希望我在上面提供了足够的内容来帮助其他人,当他们创建一个与嵌套属性有很多的关系时。

4

1 回答 1

1

几天后,我在阅读博客 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 或创建与此答案类似的块以在那里处理它。

于 2013-10-04T11:52:47.770 回答