ruby-on-rails 我如何让一个helper方法对工厂可用?(Rails,Rspec)

lyr7nygr  于 2023-03-04  发布在  Ruby
关注(0)|答案(4)|浏览(198)

我试图调用工厂内部的一个helper方法,但是它总是以找不到方法的形式返回。
/规格/助手/工厂.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和文件本身中请求,但是都返回相同的结果。我也试过不包含模块名而只包含方法名,但是也不起作用。这可能吗?

8ljdwjyq

8ljdwjyq1#

查看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)
xyhw6mcr

xyhw6mcr2#

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
mfpqipee

mfpqipee3#

您可以将其添加到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) } 
...
s8vozzvw

s8vozzvw4#

module Helpers
  module Factories
    module_function

    def array_of_fakers(faker_class, field, number_of_elements)
      # ...
    end
  end
end

或:

module Helpers
  module Factories
    def self.array_of_fakers(faker_class, field, number_of_elements)
      # ...
    end
  end
end

前者更漂亮一些,但两者都可以。因此,你可以在任何地方调用::Helpers::Factories.array_of_fakers。注意有时可能需要的前导双冒号。

相关问题