是否可以在FactoryGirl的关联(特征内)中使用嵌套工厂?

时间:2016-01-22 20:17:05

标签: ruby-on-rails rspec associations factory-bot

例如,假设我有Address嵌套工厂,belongs_to为ZipOrder有一个Address和一个理想创建的特征与其中一个嵌套工厂的关联:

  # File one with its own FactoryGirl.define do...
  factory :zip do
  end

  # File two
  factory :address do
    zip  # an address belongs_to a zip

    factory :address_variant do
    end
  end

  # File 3
  factory :order do
    trait :with_address_variant do
       address_variant  # EDIT: this was my bug :)
    end
  end

我想这样使用它:FactoryGirl.build_stubbed(:order, :with_address_variant)。但是在运行测试时我得到NoMethodError: undefined method 'address_variant='

如果我在下面建议的特性中使用FactoryGirl.build_stubbed(:address_variant),当rspec尝试初始化所有内容时,我会得到find': Factory not registered: zipcode (ArgumentError)

这甚至可以吗?

1 个答案:

答案 0 :(得分:1)

更新

我赶紧回答原来的答案。我认为这是实现你想要的正确方法:

factory :address do
  attribute "1"
end

factory :address_variant, :parent => :address do
  attribute "2"
end

factory :order do
  trait :with_address_variant do
     association :address, :factory => :address_variant
  end
end

===

试试这个:

trait :with_address_variant do
   FactoryGirl.build_stubbed(:address_variant)
end