Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include a module in a factory_girl factory?

I'm trying to reuse a helper method in all my factories, however I cannot get it to work. Here's my setup:

Helper module (in spec/support/test_helpers.rb)

module Tests
  module Helpers
    # not guaranteed to be unique, useful for generating passwords
    def random_string(length = 20)
      chars = ['A'..'Z', 'a'..'z', '0'..'9'].map{|r|r.to_a}.flatten
      (0...length).map{ chars[rand(chars.size)] }.join
    end
  end
end

A factory (in spec/factories/users.rb)

FactoryGirl.define do
  factory :user do
    sequence(:username) { |n| "username-#{n}" }
    password random_string
    password_confirmation { |u| u.password }
  end
end

If I run my tests (with rake spec), I get the following error wherever I create a user with Factory(:user):

 Failure/Error: Factory(:user)
 ArgumentError:
   Not registered: random_string

What do I have to do to be able to use random_string in my factories?

I have tried the following:

  • using include Tests::Helpers at every level of my factory (before the define, between define and factory :user and inside factory :user)
  • in spec_helper.rb, I have the following already: config.include Tests::Helpers and it gives me access to random_string in my specs
  • simply requiring the file in my factory

I have also read the following links without success:

  • Define helper methods in a module
  • Different ways of code reuse in RSpec
like image 814
mbillard Avatar asked Oct 26 '11 19:10

mbillard


1 Answers

What about a mere:

module Tests
  module Helpers
    # not guaranteed to be unique, useful for generating passwords
    def self.random_string(length = 20)
      chars = ['A'..'Z', 'a'..'z', '0'..'9'].map{|r|r.to_a}.flatten
      (0...length).map{ chars[rand(chars.size)] }.join
    end
  end
end

Then:

FactoryGirl.define do
  factory :user do
    sequence(:username) { |n| "username-#{n}" }
    password Tests::Helpers.random_string
    password_confirmation { |u| u.password }
  end
end

Ok, got it :) Do as follows:

module FactoryGirl
  class DefinitionProxy
    def random_string
     #your code here
    end
  end
end
like image 121
apneadiving Avatar answered Oct 06 '22 09:10

apneadiving