【发布时间】:2021-03-08 02:28:04
【问题描述】:
我很高兴制作 find_or_create_by 版本的 factorybot 工厂。但是,我想用一行代码(例如包含语句或方法调用)将代码添加到工厂,而不是将整个块粘贴到每个工厂。
所以我试图在 FactoryBot 中插入一个方法,但工厂只是抱怨该方法的名称不是注册的特征。如何从工厂调用方法?
class FactoryBot::Declaration::Implicit
def change_factory_to_find_or_create
# This hook allows us to do find_or_create for factories
to_create do |instance|
attributes = instance.class.find_or_create_by(instance.attributes.compact).attributes
instance.attributes = attributes.except('id')
instance.id = attributes['id'] # id can't be mass-assigned
instance.instance_variable_set('@new_record', false) # marks record as persisted
end
end
end
FactoryBot.define do
factory :my_thing do
change_factory_to_find_or_create
label { "Label One" }
end
end
【问题讨论】: