关于将选项传递给特征的 Factory Girl 语法的问题
question about Factory Girl syntax for passing an option to a trait
我正在接手一个有问答部分的项目。我正在添加联合功能,并希望建立一个问题 has_one:syndicatable_question 的关系。
对于我的工厂,我有一个 API 像 sq = FactoryGirl.create(:question, :with_syndication )
用于简单的情况,我想要像 sq = FactoryGirl.create(:question, :with_syndication(syndicatable_location_id: 345))
这样的东西,但这不起作用。我怎么能为特征传递选项/参数?我需要对工厂进行哪些更改?
我的工厂目前是这样的:
FactoryGirl.define do
factory :question, class: Content::Question do
specialty_id 2
subject { Faker::Lorem.sentence }
body { Faker::Lorem.paragraph }
location_id 24005
trait :with_syndication do
after(:create) do |q, options|
create(:syndicatable_question, question_id: q.id, syndicatable_location_id: q.location_id)
end
end
end
end
您需要将 transient
块添加到您的特征中
FactoryGirl.define do
factory :question, class: Content::Question do
specialty_id 2
subject { Faker::Lorem.sentence }
body { Faker::Lorem.paragraph }
location_id 24005
transient do
syndicatable_location_id 24005
end
trait :with_syndication do
after(:create) do |q, options|
create(:syndicatable_question, question_id: q.id, syndicatable_location_id: options.syndicatable_location_id)
end
end
end
end
FactoryGirl.create(:question, :with_syndication, syndicatable_location_id: 345)
瞬态属性
https://www.rubydoc.info/gems/factory_girl/file/GETTING_STARTED.md#Traits
我正在接手一个有问答部分的项目。我正在添加联合功能,并希望建立一个问题 has_one:syndicatable_question 的关系。
对于我的工厂,我有一个 API 像 sq = FactoryGirl.create(:question, :with_syndication )
用于简单的情况,我想要像 sq = FactoryGirl.create(:question, :with_syndication(syndicatable_location_id: 345))
这样的东西,但这不起作用。我怎么能为特征传递选项/参数?我需要对工厂进行哪些更改?
我的工厂目前是这样的:
FactoryGirl.define do
factory :question, class: Content::Question do
specialty_id 2
subject { Faker::Lorem.sentence }
body { Faker::Lorem.paragraph }
location_id 24005
trait :with_syndication do
after(:create) do |q, options|
create(:syndicatable_question, question_id: q.id, syndicatable_location_id: q.location_id)
end
end
end
end
您需要将 transient
块添加到您的特征中
FactoryGirl.define do
factory :question, class: Content::Question do
specialty_id 2
subject { Faker::Lorem.sentence }
body { Faker::Lorem.paragraph }
location_id 24005
transient do
syndicatable_location_id 24005
end
trait :with_syndication do
after(:create) do |q, options|
create(:syndicatable_question, question_id: q.id, syndicatable_location_id: options.syndicatable_location_id)
end
end
end
end
FactoryGirl.create(:question, :with_syndication, syndicatable_location_id: 345)
瞬态属性 https://www.rubydoc.info/gems/factory_girl/file/GETTING_STARTED.md#Traits