禁用特征内的FactoryGirl关联

问题描述 投票:2回答:2

在Rails应用程序中,我使用FactoryGirl来定义一般工厂以及几个更具体的特性。一般情况和除了一个特征之外的所有特征都有一个特定的关联,但是我想定义一个特征,其中不创建/构建该关联。我可以使用after回调将关联的id设置为nil,但这并不能阻止关联记录首先被创建。

在特征定义中是否有一种方法可以完全禁用为特征所属的工厂定义的关联的创建/构建?

例如:

FactoryGirl.define do
  factory :foo do
    attribute "value"
    association :bar

    trait :one do
      # This has the bar association
    end

    trait :two do
      association :bar, turn_off_somehow: true
      # foos created with trait :two will have bar_id = nil
      # and an associated bar will never be created
    end
  end
end
ruby-on-rails associations factory-bot traits
2个回答
3
投票

factory_girl中的关联只是一个与其他任何属性相同的属性。使用association :bar设置bar属性,因此您可以通过使用nil覆盖它来禁用它:

FactoryGirl.define do
  factory :foo do
    attribute "value"
    association :bar

    trait :one do
      # This has the bar association
    end

    trait :two do
      bar nil
    end
  end
end

1
投票

我尝试了@Joe Ferris的回答但看起来它在factory_bot 5.0.0中不再起作用了。我发现这个related question引用了可以传递给协会的strategy: :null标志,如:

FactoryGirl.define do
  factory :foo do
    attribute "value"
    association :bar

    trait :one do
      # This has the bar association
    end

    trait :two do
      association :bar, strategy: :null
    end
  end
end

它似乎现在就做了。

Source code看起来像只是停止任何回调,如创建或构建,所以将关联呈现为空。

module FactoryBot
  module Strategy
    class Null
      def association(runner); end

      def result(evaluation); end
    end
  end
end
© www.soinside.com 2019 - 2024. All rights reserved.