Sharing Code

Sharing code between factories in FactoryGirl takes a little bit of effort. Here’s one way of accomplishing it, which I patched together from reading this GitHub Issue:

Sharing code in FactoryGirl

First, we create a module with the shared code. Then we include it into the FactoryGirl::SyntaxRunner.

You need to put it in the spec/factories folder so that it is included when FactoryGirl is included. I put it in a subfolder spec/factories/support/ so that it is easy to differentiate between the factories and the supporting files.

So you might have a file like below:

# spec/factories/support/random_code_support.rb

# I use a namespace here so there's no chance of overriding any other class or module.
module FactoryGirlSupport
  module RandomCodeSupport
    def generate_random_code(i, min_length=6)
      rand(1000).to_s.rjust(min_length, "0") + i.to_s
    end
  end
end

# This will make the methods in the FactoryGirlSupport::RandomCodeSupport available in your factories
FactoryGirl::SyntaxRunner.send(:include, FactoryGirlSupport::RandomCodeSupport)

Now you can use the method in the module above in your factories like this:

FactoryGirl.define do
  factory :user do
    sequence(:remote_id) {|i| generate_random_code(i) }
  end
end

That’s all there is to it.