shoulda and factory_girl not cleaning up db between tests

December 22nd, 2009 by e-thang Leave a reply »

Wow, this one was a doozy. I recently (yesterday) had my first introduction to shoulda and factory_girl for testing. I’m torn as to whether or not fixtures are the root of all evil, as I haven’t really encountered problems with them and find them very simple to use and maintain, but that isn’t the point of this post.

The point is that just starting a new job I figured a good thing to do was first run the unit tests to make sure I had set up the app properly. I was treated to many failures and investigated why. I found many failures caused by a polluted database. Previous tests weren’t cleaning up after themselves, so later tests had bad state (duplicate records and that sort of thing). While that may be a plug for database level enforcement of that kind of rule, that task was beyond the scope of what I was doing.

I scoured Google looking for answers, and a day later I finally found it. Just to stretch you along even further, here’s what it wasn’t:

  • shoulda not running implicit teardowns
  • transactional fixtures being turned off

No, it was a great deal dumber than that, and a thanks to Eric Artzt, whoever you are, for providing the solution. The table that was giving me fits is a MyISAM table, which doesn’t support transactions. Which means there are no rollbacks to clean up my DB state. Which means I either have to explicitly put calls to do that into an explicity-defined teardown method or switch the engine on the table in question.

Advertisement

4 comments

  1. David says:

    Posting for completeness sake, I had the same issue and the cause was that I was extending Test::Unit::TestCase instead of ActiveSupport::TestCase.

  2. e-thang says:

    Thank you for the addition. Weird little things like this can be so frustrating; it’s nice to collect a little repository of solutions. Happy coding to you sir!

  3. Matt Powell says:

    We’re having the same problem with Rails 3.1.rc4 and Postgres. Without any context blocks the fixtures roll back just fine, but with them the DB never gets rolled back. Big pain in the neck.

    We’ve tried the “context” gem as well as “shoulda” for our context blocks. It’s always worked fine for us on Rails 2.3.x. Anyone got any futher ideas? Will also post on Shoulda forums.

  4. Eric Wanchic says:

    Same Problem: Rails 3.1.rc4 and Postgres. Running a rake db:test:prepare before a unit test helps…annoying. rake test at cmd has no problems though, and I’m using RubyMine 3.2.2. Already extending ActiveSupport::TestCase. So, I’m not sure where the issue is exactly.

Leave a Reply