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

时间:2018-09-18 11:31:59

标签: ruby-on-rails ruby factory-bot rspec-rails

我有一个扩展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

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_createFactoryBot.first_or_create没有帮助
  • include在FactoryBot模块中对其没有帮助
  • config.include中的
  • RSpec.configure无济于事
  • 我什至无法直接访问它FactoryBot::SyntaxHelper.first_or_create

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

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

1 个答案:

答案 0 :(得分:0)

每个@engineersmnky,extend表示FactoryBot有效

module FactoryBot
  extend FactoryBotFirstOrCreate
end

然后这有效

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