I’ve been jumping into Ruby (and specifically Rails) testing in the last few weeks. I figured I’d share a quick introduction to a neat tool that really has the potential to save time: FactoryGirl.
FactoryGirl is a gem that allows you to replace cumbersome Rails fixtures with something much more flexible. When testing, fixtures allow you to specify some default entries in your database tables which can then be used throughout your tests. Read more about fixtures here. A fixtures file might look something like this.
Fixtures are automatically loaded when tests are run. Inside my tests, I would be able to use my fixtures like so.
require'test_helper'classUserTest<ActiveSupport::TestCasetest'Bob should be the CEO'doassert_equalusers(:bob).position,'CEO'endend
This is all well and good until you suddenly need to do something slightly outside of the box. What if you want to quickly generate 3 more test users with unique names? What if you need a large array of 100 test users? Fixtures don’t work particularly well in these kinds of scenarios. Of course, you could also write these particulars into your test’s setup method. But there’s an easier way. Enter FactoryGirl.
In this one example, I’ve taken care of all of the afore mentioned hypothetical scenarios while still including our original fixtures. Each model can be associated with many factories. A factory allows you to manufacture lots of objects of your model class. Here’s how I might use the factories I defined in place of the earlier unit test.
require'test_helper'classUserTest<ActiveSupport::TestCasetest'Run some test examples'do# Let's get John and Bob back from the original fixturesbob=FactoryGirl.create(:user_bob)john=FactoryGirl.create(:user_john)# Now let's create 100 unique usersusers=FactoryGirl.create_list(:user,100)# I need a new unique user named Jimjim=FactoryGirl.create(:named_user,first_name:'Jim',last_name:'Smith')# Both of these will passassert_equaljim.email,'firstname.lastname@example.org'assert_equalusers.first.email,'email@example.com'endend
Not only have I easily generated some unique users for my tests, but I can sequence unique email addresses for each one with just a couple lines of code in my factory definition. This is just scratching the surface of what can be done with FactoryGirl. It has support for callbacks, associations, and so much more.