Factory_Girl Validation Trouble

I ran into a dilemma with one of my rspec controller test suites while working on a personal website with book and author models.

It occurred as I was using the amazing factory_girl gem, which allows me to pre-define the attributes for a model into a factory to be used over and over again throughout my test suite. That way any time I need to fire up a test instance of a particular model, I can very easily with code like:

@whatever = FactoryGirl.create(:whatever)

Here’s a link to factory girl, I’d highly recommend it:


Now, my issue occurred because I was creating a user factory with the following code prior to each test in the book’s controller spec.

@user = FactoryGirl.create(:user)

I kept getting a validation error, because my Factory was trying to create users with the same email for each new test. This was bad because I was validating for unique email in my model.

Through some clever Google searching, I finally ran into a wonderful RailCast video that pointed me in the right direction:


After watching the video, I discovered that I needed to update the email assigning portion of my factory to look like the following:

FactoryGirl.define do
factory :user do |f|
f.name "foo"
f.sequence(:email) {|n| “foo#{n}@example.com”}

That bolded line had previously just been

f.email "foo@example.com"

As you can probably tell, I’m now creating a unique email based on the value “n” that got me out of the validation trouble I’d found myself in.

Thank’s RailCasts!

Tagged , ,

One thought on “Factory_Girl Validation Trouble

  1. […] me in on a little trick that I’d like to share. When testing, it’s a good idea to have factories written for each model. Now, if your model is already created, you’ll have to spin up that factory […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: