【问题标题】:Disabling a FactoryGirl association within a trait在 trait 中禁用 FactoryGirl 关联
【发布时间】:2013-11-08 18:02:29
【问题描述】:

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

在 trait 定义中是否有办法完全禁止创建/构建已为 trait 所属的工厂定义的关联?

例如:

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

【问题讨论】:

  • 嗯,不确定我是否理解正确。你是说你在使用FactoryGirl创建模型实例的时候,要禁止Rails在创建模型实例的时候调用创建其他关联模型实例的回调??
  • @dmtri.com:我添加了一个示例,这有助于解释我想要做什么吗?

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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我尝试了@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
    

    【讨论】:

    • 如果协会允许,我相信你也可以只做bar { nil }:验证
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    相关资源
    最近更新 更多