How split factory_girl definitions across many files?

factory-bot, ruby-on-rails

Solution

You can simply achieve the result with `generate` method:

# factories/sequences.rb
FactoryGirl.define do
  sequence(:email) { |n| "person#{n}@example.com" }
end

# factories/user.rb
FactoryGirl.define do
  factory :user do
    email { generate(:email) }
    password '12345678'
  end
end

Then try it:

FactoryGirl.create :user
=> #<User:0x007fa99d2ace40
 id: 1,
 email: "person1@example.com",
 . . .>

Sequences Documentation for more details.

Problem

My `factories.rb` file became too big to maintain over time and I'm now trying to split it across many files in `factories` directory. The problem is that I don't know how to deal with dependencies. To make a long story short, I'm trying to split my factories in following way. All sequences go to `sequences.rb` file and each factory definition goes to separate file like so: factories/sequences.rb ``` FactoryGirl.define do sequence :name {|n| "Name #{n}" } sequence :email {|n| "person#{n}@example.com" } end ``` factories/user.rb ``` FactoryGirl.define do factory :user do name email end end ``` factories/post.rb ``` FactoryGirl.define do factory :post do name content "Post Content" user end end ``` When I run tests I get `name` is not defined error. I can deal with this by passing a block to each association (e.g. `name`, `email`, `user` and so on) mention but it seems to be ugly and not DRY. - Is there way to let `factory_girl` know sequence in which files should be loaded? - to deal with complex dependencies when it's not possible to fix this issue with changing load sequence of files?

Original source