jrd*_*oko 5 ruby-on-rails associations traits factory-bot
在 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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)