Ruby on rails 使用RSPEC和FactoryGirl测试Rails的深层嵌套属性

Ruby on rails 使用RSPEC和FactoryGirl测试Rails的深层嵌套属性,ruby-on-rails,rspec,factory-bot,nested-attributes,has-many-through,Ruby On Rails,Rspec,Factory Bot,Nested Attributes,Has Many Through,我需要一些帮助,使我的工厂女孩设置正确的这有一个通过许多嵌套属性。这里有三个模型供参考 location.rb class Location < ActiveRecord::Base has_many :person_locations has_many :people, through: :person_locations end class PersonLocation < ActiveRecord::Base belongs_to :person belong

我需要一些帮助,使我的工厂女孩设置正确的这有一个通过许多嵌套属性。这里有三个模型供参考

location.rb

class Location < ActiveRecord::Base
  has_many :person_locations
  has_many :people, through: :person_locations
end
class PersonLocation < ActiveRecord::Base
  belongs_to :person
  belongs_to :location
  accepts_nested_attributes_for :location, reject_if: :all_blank
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>
FactoryGirl.create(:person,:location_1)
未定义的方法“位置\属性”#
此外,我希望能够正确测试我的控制器设置,以创建一个具有嵌套位置的新用户。如果我不能把电话缩短到一条线,这将很难做到


谢谢你的帮助!!希望我在上面提供了足够的信息,以帮助其他人创建一个具有嵌套属性的多通关系

几天后,我读了一遍又一遍,终于明白了。现在正在重构我所有的FactoryGirl代码

FactoryGirl应如下所示:

factory :person do 
...
  trait :location_1 do 
    after(:create) do |person, evaluator|
      create(:person_location, :location_1, person: person)
    end
  end
end
工厂的人员位置应该非常直接,然后遵循上述代码。您可以执行原始问题中的location_属性,也可以创建一个与此答案类似的块来处理它

另一个好的资源是
FactoryGirl.create(:person, :location_1)

   undefined method `location_attributes' for #<FactoryGirl::SyntaxRunner:0x007fd65102a380>
factory :person do 
...
  trait :location_1 do 
    after(:create) do |person, evaluator|
      create(:person_location, :location_1, person: person)
    end
  end
end