Rails FactoryGirl 实例变量

Rails FactoryGirl instance variable

我想使用局部变量创建工厂。 目前我有以下工厂:

FactoryGirl.define do
  factory :offer_item, class: BackOffice::OfferItem do
    service
    variant
  end
end

我的期望是创建如下内容

 FactoryGirl.define do
    variant = FactroyGirl.create(:variant)
    factory :offer_item, class: BackOffice::OfferItem do
      service
      variant { variant }

      after(:create) do |offer_item|
        offer_item.service.variants << variant
      end
    end
  end

但后来我得到:

/.rvm/gems/ruby-2.2.3/gems/factory_girl-4.7.0/lib/factory_girl/registry.rb:24:in `find': Factory not registered: variant (ArgumentError)

所有模型都嵌套在 BackOffice 模块中。通常我希望同一个对象与其他两个对象关联。我认为我工厂的范围存在一些问题。

变体工厂在其他单独的文件中。

问题是您试图在 FactoryGirl 完成加载所有工厂定义之前创建工厂。这是因为您在工厂定义的范围内定义了变量。即使这确实有效,您也可能最终会在测试中创建的多个 offer_items 之间共享相同的变体记录,因为此代码只会在初始化期间执行一次。

由于您定义了与 Variant 的关联,您可能不需要将其创建为额外步骤。我们可以利用 FactoryGirl 的能力为我们创建关联,然后将对象复制到 #service 回调中的 after(:create)。也许它看起来像这样(未经测试):

FactoryGirl.define do

  factory :offer_item, class: BackOffice::OfferItem do
    service
    variant

    after(:create) do |offer_item|
      offer_item.service.variants << offer_item.variant
    end
  end
end