How can I add a function to FactoryBot globally?

落爺英雄遲暮 提交于 2021-01-28 11:00:51

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/52385642/how-can-i-add-a-function-to-factorybot-globally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!