【问题标题】:Testing Rails Deep Nested Attributes with RSPEC and FactoryGirl使用 RSPEC 和 FactoryGirl 测试 Rails 深层嵌套属性
【发布时间】:2013-10-02 23:14:14
【问题描述】:

我需要一些帮助来正确设置我的 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

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

注意locations嵌套在person记录下,但是需要经过两个model才能嵌套。我可以像这样进行测试:

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>

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

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

【问题讨论】:

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


    【解决方案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 或创建与此答案类似的块以在那里处理它。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多