gpt4 book ai didi

ruby-on-rails - 如何覆盖 factory_girl 中的委托(delegate)属性?

转载 作者:太空宇宙 更新时间:2023-11-03 16:44:26 25 4
gpt4 key购买 nike

我有一个属性委托(delegate)给关联对象 (AR/Postgres),并试图在调用工厂时覆盖它。

class Patient
delegate :email, to: :credential
has_one :credential, as: :owner, dependent: :destroy
end

class Credential
belongs_to :owner, polymorphic: true
end

FactoryGirl.define do
factory :patient do
first_name 'Jane'
last_name 'Patient'
dob Date.parse('2005-01-11')
gender 'Female'
zipcode '80202'

after(:build) do |user|
create(:credential, owner: user)
end
end
end

FactoryGirl.define do
factory :credential do
password '!Secret15'
password_confirmation { password }
agree_to_terms true

sequence :email do |n|
"user#{n}@bar.com"
end
end
end

调用:

create(:patient, email: 'new@email.com')

它根本不起作用,属性正在按默认顺序设置。

搜索了他们的文档和谷歌,但找不到答案。非常感谢任何帮助。

最佳答案

factory_girl 不对 delegate 做任何事情。您需要自己将 email 传递给 :credential 工厂。属性在回调中不可用,因此从评估器获取 email,这是回调 block 的第二个参数:

FactoryGirl.define do
factory :patient do
# other attributes

after(:build) do |user, evaluator|
create(:credential, owner: user, email: evaluator.email)
end
end
end

记录在此处:https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#transient-attributes

关于ruby-on-rails - 如何覆盖 factory_girl 中的委托(delegate)属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37120733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com