如何在全局范围内向 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

但是当我试图在工厂外使用它时,我无法访问它...

完成所有这些步骤后,我仍然得到 NoMethodError: undefined method first_or_create

我可以包括什么或以其他方式配置以使我可以像 FactoryGirl 的 create 一样访问此方法?

根据@engineersmnky,extending FactoryBot 工作

module FactoryBot
  extend FactoryBotFirstOrCreate
end

然后这有效

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