如何向FactoryBot全局添加功能?

问题描述 投票:0回答:2

我有一个类,它扩展了 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_create
    FactoryBot.first_or_create
    没有帮助
  • include
    在 FactoryBot 模块中使用它没有帮助
  • config.include
    RSpec.configure
    没有帮助
  • 我什至无法直接访问它
    FactoryBot::SyntaxHelper.first_or_create

完成所有这些步骤后,我仍然得到

NoMethodError: undefined method first_or_create

我可以包含什么或以其他方式配置以允许我像 FactoryGirl 的

create
一样访问此方法?

ruby-on-rails ruby factory-bot rspec-rails
2个回答
0
投票

每@engineersmnky,

extend
ing FactoryBot 有效

module FactoryBot
  extend FactoryBotFirstOrCreate
end

然后就可以了

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

0
投票

这在初始化文件中对我有用:

module SystemRecords
  def system_authentication_user
    AuthenticationUser.system
  end

  def system_platform_tenant
    PlatformTenant.system
  end

  def system_user_profile
    UserProfile.admin_role
  end

  def system_user
    User.system
  end
end

module FactoryBot
  class SyntaxRunner
    include SystemRecords
  end
end

我现在可以做:

FactoryBot.define do
  factory :some_record, class: SomeClass do
    platform_tenant { system_platform_tenant }
    created_by { system_user_profile }
    updated_by { created_by }
    authentication_user { system_authentication_user }
  end
end
© www.soinside.com 2019 - 2024. All rights reserved.