Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How split factory_girl definitions across many files?

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.

  1. Is there way to let factory_girl know sequence in which files should be loaded?
  2. to deal with complex dependencies when it's not possible to fix this issue with changing load sequence of files?
like image 598
luckyjazzbo Avatar asked May 26 '14 03:05

luckyjazzbo


2 Answers

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: "[email protected]",
 . . .>

Sequences Documentation for more details.

like image 191
itsnikolay Avatar answered Oct 15 '22 01:10

itsnikolay


I do this in this way:

  1. Create separate folder for shared factories. It should in same level as 'factories' folder.

factories

shared_factories

  1. Create shared file, ex. shared_factories/sequences.rb

  2. Import sequences.rb to every factory file. require_relative '../shared_factories/sequences'

The full example:

https://gist.github.com/alexkojin/6a2d70f84ff91c37315d1d3edb0d8e6b

like image 22
Alex Kojin Avatar answered Oct 15 '22 00:10

Alex Kojin