问题
I have a class that extends FactoryBot to include functionality to copy 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
I can add that to the SyntaxRunner
class
module FactoryBot
class SyntaxRunner
include FactoryBotFirstOrCreate
end
end
to access it in factories
# ...
after(:create) do |thing, evaluator|
first_or_create(:other_thing, thing: thing)
end
But when I attempt to employ this outside of factories, I can't access it...
FactoryBot::SyntaxRunner.first_or_create
orFactoryBot.first_or_create
doesn't helpinclude
ing it in the FactoryBot module doesn't helpconfig.include
inRSpec.configure
doesn't help- I can't even access it directly
FactoryBot::SyntaxHelper.first_or_create
With all of those steps in place, I still get NoMethodError: undefined method first_or_create
What can I include or otherwise configure to allow this method to be as accessible to me as FactoryGirl's create
?
回答1:
Per @engineersmnky, extend
ing FactoryBot works
module FactoryBot
extend FactoryBotFirstOrCreate
end
then this works
my_foo = first_or_create(:everything, is: :awesome, if_we: :work_together)
来源:https://stackoverflow.com/questions/52385642/how-can-i-add-a-function-to-factorybot-globally