Friday, January 15, 2010

VICTORY: FactoryGirl and Database Rollbacks that Failed

Draw near my children and listen to a terrible tale of trial, tribulation, twisting torment, teething, temper-tantrums, truculence, and truancy. Except the teething part. And there may have been truffles.

Seriously, I was ready to walk away from FactoryGirl. Perhaps you have heard of FactoryGirl, yes? Perhaps you have encountered records left in the database after the test completes. Perhaps you Google for all sorts of phrases like "FactoryGirl records left database" or "FactoryGirl rollback". Perhaps you scoured Google groups, the rdocs and all of that stuff. Yah, me too.

Yes, "use_transactional_fixtures" was true and "use_instantiated_fixtures" was false. I searched the entire code base. So did you.

But, I'm using rspec, so there is no test_helper. Spec_helper has slightly different syntax from test_helper, so "self.use_transactional_fixtures" won't work. You're using FactoryGirl, so you don't have any fixtures. I deleted mine; get that cruft out of the way. Heck, I deleted my entire test directory!

But I finally got it. And it seems so easy now. Like childs play, just like in Spock's Brain, when McCoy had to re-attach Spock's brain. And, hopefully this will help you too.

Make sure you have a fixtures directory. Mine is in RAILS_ROOT/spec, so I added the following line to my spec_helper.rb:

config.fixture_path = RAILS_ROOT + '/spec/fixtures/'

Then I told Spec::Runner that I had fixtures, even though the directory is empty! There is a fixture entry for every table that was not getting reset. For example, the users table was not getting reset, so I set:

config.global_fixtures = :users

And, when I needed the players table cleared, I added the following:

config.global_fixtures = :users, :players

That's it! All better. Rspec now clears up those tables just as purty as you please and the tests are passing -- big bars o' green! Yippee!

No comments:

Post a Comment