如何在全局范围内向 FactoryBot 添加功能?
How can I add a function to FactoryBot globally?
我有一个 class 扩展 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
class
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
一样访问此方法?
根据@engineersmnky,extend
ing FactoryBot 工作
module FactoryBot
extend FactoryBotFirstOrCreate
end
然后这有效
my_foo = first_or_create(:everything, is: :awesome, if_we: :work_together)
我有一个 class 扩展 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
class
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
一样访问此方法?
根据@engineersmnky,extend
ing FactoryBot 工作
module FactoryBot
extend FactoryBotFirstOrCreate
end
然后这有效
my_foo = first_or_create(:everything, is: :awesome, if_we: :work_together)