Hey, flexmock and unit_record, play nice!

So you’re savvy with flexmock, a fine Rails plugin that lets you create mock objects in your tests. You’ve been coding up a boatload of fine tests that are elegant in their isolation thanks to your super mocks. They all run fine, but they’re kind of slow so you go Googling for techniques to speed them up.

You stumble across a wonderful plugin called unit_record that can dramatically speed up your unit tests by disconnecting them from the database. You install it, run your tests, and wham, you get a barrage of error messages like this:

ActiveRecord is disconnected; database access is unavailable in unit tests.

There could be one or two things going on here. The first possibility is that one or more of your unit tests are still attempting to access the database via a finder or a fixture. This is the most likely case if you’re only getting a few errors. If you’re getting an error for every single unit test in your suite, though, then something else is going on: flexmock is not playing nicely with unit_record.

The root of the problem is that unit_record attempts to turn off transactional fixtures for your unit tests when you run them, but flexmock hijacks unit_record by defining its own alias chains for setup/teardown.

I got around this problem by updating my unit_test_helper.rb file to include the following:

class Test::Unit::TestCase
  self.use_transactional_fixtures = false

It’s unfortunate this has to be done, but it’s a better option than digging into the flexmock plugin itself… especially if you plan on upgrading to a new version of flexmock anytime soon. Don’t forget that you should be disconnecting ActiveRecord in your unit_test_helper.rb as well. This is what my entire file looks like:

require File.dirname(__FILE__) + '/../test_helper'

require 'unit_record'

class Test::Unit::TestCase
  # Unit_record is trying to do this for us, but since we're
  # using flexmock's test case it patches the wrong class.
  self.use_transactional_fixtures = false

Hope this helps someone who was as equally stumped as I was. Happy testing!

Update on 12/1/07: After chatting with Jim Weirich (the creator of flexmock) and doing some more tweaking, it became obvious that the problem is not with flexmock but lies somewhere else. I removed all references to flexmock from my code and still had trouble. The transactional fixture switch seems to be getting set between test runs, but I can’t locate where it’s happening. If anyone else finds a solution to this problem, please let us know by posting a comment here.

One thought on “Hey, flexmock and unit_record, play nice!

  1. Pingback: casinò microgaming

Comments are closed.