Fork me on GitHub

July 20, 2010

Disabling Test Fixtures

Post moved to http://log2.kares.org/post/59891239111/disabling-test-fixtures

Once upon a time in a west land of Fixtures lived a doubtful engineer. Luckily for him, he was a believer and believed the right way of doing things was chosen by the wiser. He followed the graceful path for a long time, long enough to get lost and realize how nasty things were. Until suddenly one day he knew he can't handle it anymore. And that was the beginning of the obligatory end of Fixtures as we know it ...

When You're a newbie into Ruby on Rails, there's a lot of knowledge "distractions" and it takes a while, even for a experienced developer to form a sober opinion. Rails advocates testing and provides fixtures as a source of test data. I did find this approach misleading. As Your tests grow managing the test data become hard. Having shared test data might be very reasonable for integration tests, but in functional and especially in unit tests the test data might turn out difficult to manage cause of all the corner cases to be tested.

There are testing practices and patterns for overcoming fixtures, but what if You have an existing code base and start migrating slowly towards non-fixture dependent tests. If You decide to go far enough and disconnect Your unit tests from the database and use mocking extensively - good for You, the old tests might happily live with the new ones. If You're like me and create the test data required as part of the test similar to the data factory approach, You might get surprised from time to time. The existing fixtures data (required for the "old" tests) might still be there loaded in the database and might interfere with the "new" data. It would be best if we could disable Rails test fixtures per test. Turns out we can, thanks to my disable_test_fixtures plugin. Here's a gist of using it:



And all the Fixtures developers lived happily ever after by the golden rule of testing: "An imperfect test today is better than a perfect test someday".

2 comments:

  1. Hi, thanks for your helpful post.
    I would like to know if we have a similar way to disable fixture with Rspec.

    ReplyDelete
  2. In your RSpec example group, or context...

    def setup_fixtures
    end

    def teardown_fixtures
    end

    This overrides the default behaviour included from the ActiveRecord::TestFixtures module that is included into each RSpec test.

    ReplyDelete