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.
factory_girl
know sequence in which files should be loaded?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.
I do this in this way:
factories
shared_factories
Create shared file, ex. shared_factories/sequences.rb
Import sequences.rb
to every factory file.
require_relative '../shared_factories/sequences'
The full example:
https://gist.github.com/alexkojin/6a2d70f84ff91c37315d1d3edb0d8e6b
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With