Search code examples
ruby-on-railsrubyfactory-botrspec-rails

How can I add a function to FactoryBot globally?


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 or FactoryBot.first_or_create doesn't help
  • includeing it in the FactoryBot module doesn't help
  • config.include in RSpec.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?


Solution

  • Per @engineersmnky, extending FactoryBot works

    module FactoryBot
      extend FactoryBotFirstOrCreate
    end
    

    then this works

    my_foo = first_or_create(:everything, is: :awesome, if_we: :work_together)