如何为工厂提供辅助方法?(导轨、Rspec)

Car*_*arl 4 ruby rspec ruby-on-rails factory-bot

我试图在工厂内部调用辅助方法,但它始终返回为未找到方法。这是辅助方法

/spec/helpers/factories.rb

module Helpers
  module Factories

    def array_of_fakers(faker_class, field, number_of_elements)
      faker_array = Array.new
      number_of_elements.times do
        factory_array.push(class_eval(faker_class).send(field))
      end
      faker_array
    end

  end
end
Run Code Online (Sandbox Code Playgroud)

它被称为这样......

factory :salesman do
    clients { Helpers::Factories.array_of_fakers("Faker::Company", "name", rand(1..5)) }
    ...
end
Run Code Online (Sandbox Code Playgroud)

我尝试过在rails_helper、spec_helper 和文件本身中进行要求,但都返回相同的结果。我也尝试过不包含模块名称而仅包含方法名称,但这也不起作用。这可能吗?

gan*_*elo 6

查看factory_bot GETTING_STARTED.md文档中推荐的spec/support/factory_bot.rb配置文件设置...

就我而言,我没有使用 Rails,但这对我有用:

# spec/support/factory_bot.rb
    
# frozen_string_literal: true
    
require 'factory_bot'

# Add this...
#
# Require the file(s) with your helper methods. In my case, the
# helper methods were under Support::FileHelpers.
require_relative 'file_helpers'
    
# This is just the standard setup recommended for inclusion in a non-rails app.
RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods
    
  config.before(:suite) do
    FactoryBot.find_definitions
  end
end

# ...and this...
# Include your helpers.
FactoryBot::SyntaxRunner.send(:include, Support::FileHelpers)
Run Code Online (Sandbox Code Playgroud)