[英]How to run a method in FactoryBot?
我很高兴能制作一个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
答案是打开了错误的class。 它应该是:
class FactoryBot::DefinitionProxy
def my_custom_method
...
end
end
FactoryBot.define do
factory :my_thing do
my_custom_method
label { "My Label" }
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.