Future on Rails

Using Rails

The Widespread Abuse of Fixtures

leave a comment »

I thought, everyone on this planet already knew about the purpose of fixtures in Rails…unfortunately I see  the abuse of fixtures in many projects out there.

Fixtures are used by developers for many purposes: unit testing, integration testing or populating the DB with default data. But from all these usage scenarios, fixtures are really only good for integration testing! Don’t use fixtures for unit testing! Don’t use fixtures for populating the DB with default data!

Why not to use fixtures for unit testing?

Fixtures for unit testing is a bad idea. The main reason is that your unit tests become hard to read, because you need two code artefacts to understand them. You also introduce a dependency between test and fixtures (and between this test and other tests using the same fixture data!). It is recommended by most developers, to build unit test objects directly in the test class. This makes every test precondition explicit in the code. It is also easy, because you usually only need an object of one class (without associations).

Why not use fixtures for populating the DB?

It is also very common, to use fixtures for loading default or sample data into the database. But since fixtures are also used for (automated) testing, you might want to separate those two concerns. My recommendation is to use fixtures exclusively for automated integration testing and to use a rake task to populate the DB with default data or test data for manual testing. By using gems like Populator and Faker, you can also quickly create sensible, randomized test data, so that your human testers can do their job. See the great Railscast on “Populating a Database”.

Written by Matthias Orgler

May 11, 2009 at 1:03 pm

Posted in Uncategorized

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 )

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s

%d bloggers like this: