我有一个扩展FactoryBot的类,以包含复制Rails的.first_or_create
的功能。
module FactoryBotFirstOrCreate
def first(type, args)
klass = type.to_s.camelize.constantize
conditions = args.first.is_a?(Symbol) ? args[1] : args[0]
if !conditions.empty? && conditions.is_a?(Hash)
klass.where(conditions).first
end
end
def first_or_create(type, *args)
first(type, args) || create(type, *args)
end
def first_or_build(type, *args)
first(type, args) || build(type, *args)
end
end
我可以将其添加到SyntaxRunner
类
module FactoryBot
class SyntaxRunner
include FactoryBotFirstOrCreate
end
end
在工厂访问它
# ...
after(:create) do |thing, evaluator|
first_or_create(:other_thing, thing: thing)
end
但是当我尝试在工厂外使用此软件时,我无法访问它...
FactoryBot::SyntaxRunner.first_or_create
或FactoryBot.first_or_create
没有帮助include
在FactoryBot模块中对其没有帮助config.include
中的RSpec.configure
无济于事FactoryBot::SyntaxHelper.first_or_create
完成所有这些步骤后,我仍然可以获得NoMethodError: undefined method first_or_create
我可以包括什么或进行其他配置以使我可以像FactoryGirl的create
一样访问此方法?
答案 0 :(得分:0)
每个@engineersmnky,extend
表示FactoryBot有效
module FactoryBot
extend FactoryBotFirstOrCreate
end
然后这有效
my_foo = first_or_create(:everything, is: :awesome, if_we: :work_together)