禁用特征中的FactoryGirl关联 [英] Disabling a FactoryGirl association within a trait
问题描述
在Rails应用程序中,我正在使用FactoryGirl定义常规工厂以及其他一些特定特征.一般情况下,除了一个特征外,所有特征都有一个特定的关联,但我想定义一个不创建/构建该关联的特征.我可以使用after
回调将关联的id
设置为nil
,但这不会阻止关联记录的创建.
In a Rails app, I'm using FactoryGirl to define a general factory plus several more specific traits. The general case and all but one of the traits have a particular association, but I'd like to define a trait where that association is not created/built. I can use an after
callback to set the association's id
to nil
, but this doesn't stop the association record from being created in the first place.
特征定义中是否有一种方法可以完全禁用已为该特征所属的工厂定义的关联的创建/建立?
Is there a way in a trait definition to completely disable the creation/building of an association that has been defined for the factory the trait belongs to?
例如:
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
覆盖它来禁用它:
An association in factory_girl is just an attribute like any other. Using association :bar
sets the bar
attribute, so you can disable it by overriding it with 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
这篇关于禁用特征中的FactoryGirl关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!