Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 411
Carl Avatar asked Oct 19 '25 01:10

Carl


2 Answers

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)
like image 188
gangelo Avatar answered Oct 21 '25 17:10

gangelo


module Helpers
  module Factories
    module_function

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

or:

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

The former is prettier IMO, but either should work. In a result, you can call ::Helpers::Factories.array_of_fakers from anywhere. Note the leading double colon which may be needed sometimes.

like image 40
skalee Avatar answered Oct 21 '25 15:10

skalee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!