繁体   English   中英

如何让工厂可以使用辅助方法? (导轨,Rspec)

[英]How do I make a helper method available to factories? (Rails, Rspec)

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

/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

它被称为这样...

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

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

FactoryBot::DefinitionProxy包含您的辅助模块:

# spec/helpers/factories.rb

module Helpers
  module Factories

    def array_of_fakers(faker_class, field, number_of_elements)
      # ...
    end
  end
end
# spec/support/factory_bot_extension.rb
# (or any other file that gets required in spec/spec_helper.rb)

require_relative './helpers/factories'

FactoryBot::DefinitionProxy.send(:include, Helpers::Factories)
# spec/factories/salesman.rb

factory :salesman do
  clients { array_of_fakers("Faker::Company", "name", rand(1..5)) }
  ...
end

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

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

# 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)

您可以将其添加到您的spec/factories文件夹

FactoryBot.define do
  sequence(:id) { SecureRandom.uuid }
  sequence(:email) { Faker::Internet.unique.safe_email }
  sequence(:name) { Faker::Name.name }
end

然后在你的工厂中这样调用它:

FactoryBot.define do
  factory :my_factory do
    uuid { generate(:id) }
    name { generate(:name) } 
    email { generate(:email) } 
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM