我很高兴能制作一个find_or_create_byfactorybot 工厂版本。但是,我想用一行(例如,包含语句或方法调用)将代码添加到工厂,而不是将整个块粘贴到每个工厂。
所以我试图将一个方法插入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