禁用特征中的 FactoryGirl 关联

2024-01-01

在 Rails 应用程序中,我使用 FactoryGirl 定义一个通用工厂以及几个更具体的特征。一般情况和除一个特征之外的所有特征都具有特定的关联,但我想定义一个不创建/构建该关联的特征。我可以使用after设置关联的回调id to 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

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

禁用特征中的 FactoryGirl 关联 的相关文章

随机推荐