How to include a module in a factory_girl factory?

我们两清 提交于 2019-12-03 05:17:40

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

apneadiving's answer did not work for me. I had to do the following:

# /spec/support/factory_helpers.rb
module FactoryHelpers
  def my_helper_method
    # ...
  end
end

FactoryGirl::Proxy.send(:include, FactoryHelpers)

Then you can use it as follows:

FactoryGirl.define do
  factory :post do
    title { my_helper_method }
  end
end

I tested other answers yesterday (24.04.2012) and... none of them actually works.

Looks like Factory Girl gem (v3.2.0) have changed a lot.

But I figured out a quick solution:

# factories.rb
module FactoryMacros
  def self.create_file(path)
    file = File.new(path)
    file.rewind
    return ActionDispatch::Http::UploadedFile.new(:tempfile => file,
                                            :filename => File.basename(file))
  end
end
# also factories.rb
FactoryGirl.define do

  factory :thing do |t|
    t.file { FactoryMacros::create_file("path-to-file")
  end
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!