Start small and compose: A strategy for using FactoryGirl

March 5, 2013 John Barker

While I’m still not entirely sold on FactoryGirl, I often see it being used in a particularly lazy way. Imagine your basic factory:

factory :project

Before long you’re adding relations to projects, and the first thing people do is this:

factory :project do
  association :user
end

This immediately means that every single time you instantiate a project, you’re getting a user as well. In most cases this is more than you want, and if you continue to follow down this path you end up with a huge slow test suite. I prefer a slightly different strategy: start small and compose.

factory :project do
  ...
end

trait :with_manager do
  association :user, factory: :manager
end

This defines a very simple factory :project which gives you only a project and allows you to build a project with an associated user like so:

FactoryGirl.create(:project, :with_manager)

The result is a couple more arguments when you use the factory, but the overall code is more intention revealing.

If this is too much, you could always create a more descriptive factory:

factory :managed_project, parent: :project, traits: [:with_manager]

If you stick with this strategy, you’ll find that tests are more concise, factories are more useful and your test suite run time won’t grow as fast.

About the Author

Biography

More Content by John Barker
Previous
Why Platform should influence, NOT dictate mobile product design
Why Platform should influence, NOT dictate mobile product design

When a company chooses to engage its customers through mobile channels, the dilemma of designing the applic...

Next
LLVM, XCode's Super Secret Bug Detector
LLVM, XCode's Super Secret Bug Detector

So if you’re anything like me you get a lump in your throat and a cold sweat every time you are about to h...

Enter curious. Exit smarter.

Register Now