关于将选项传递给特性的Factory Girl语法的问题



我正在接手一个有问答部分的项目。我正在添加一个联合功能,并希望有一个问题只有一个的关系:syndicatable_question。

事实上,对于简单的情况,我有一个类似sq = FactoryGirl.create(:question, :with_syndication )的API,并且想要类似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

最新更新