如何在全球范围内向FactoryBot添加功能?

如何在全球范围内向FactoryBot添加功能?

问题描述:

我有一个扩展FactoryBot的类,该类包含复制Rails的 .first_or_create 的功能.

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

我可以将其添加到 SyntaxRunner

module FactoryBot
  class SyntaxRunner
    include FactoryBotFirstOrCreate
  end
end

在工厂访问它

# ...
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 FactoryBot.first_or_create 无效
  • 包括在FactoryBot模块中没有帮助
  • RSpec.configure 中的
  • config.include 没有帮助
  • 我什至无法直接访问它 FactoryBot :: SyntaxHelper.first_or_create
  • 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

完成所有这些步骤后,我仍然得到 NoMethodError:未定义的方法first_or_create

With all of those steps in place, I still get NoMethodError: undefined method first_or_create

我可以包括什么或进行其他配置以允许我像FactoryGirl的 create 一样方便地使用此方法?

What can I include or otherwise configure to allow this method to be as accessible to me as FactoryGirl's create?

每个@engineersmnky,扩展使FactoryBot正常运行

Per @engineersmnky, extending FactoryBot works

module FactoryBot
  extend FactoryBotFirstOrCreate
end

那么这行得通

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