简体   繁体   中英

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

I am attempting to invoke a helper method inside of a factory, but it consistently comes back as method not found. Here is the helper method

/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

it is called like this...

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

I have tried requiring in rails_helper, spec_helper and the file itself, but all return the same results. I have also tried it without including the module names and just the method name, but that doesn't work either. Is this possible?

Include your helper module in 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

Check out the spec/support/factory_bot.rb config file setup recommended in the factory_bot GETTING_STARTED.md doc...

In my case, I was not using rails, but this worked for me:

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

You can add this to your spec/factories folder

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

And then just call it in your factories like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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