Testing in Rails: Part 6 - Fixtures
Friday, December 21st, 2007This is part of an ongoing series of posts about how to get started writing tests for Ruby on Rails. The series begins with the introduction and overview of the ideas behind testing.
Fixtures
In the most general terms, a test fixture is an environment for running tests which is in a fixed state (i.e. it is ‘fixed’). While the term is primarily associated with software development, it applies to any testing environment.
Think back to our car battery example for a moment. If we unit test the battery inside the car, there is a chance that our testing environment will throw off the results. Ideally, we would remove the battery from the car and put it in a test environment that we know is stable, thereby removing as many variables and potential sources of error as possible. Then our unit test results should be predictable, accurate and repeatable. The environment we put the battery in—the meters, the wires attached to it, the amount of voltage we put in or out, etc.—is the test fixture. It will stay the same during each test we run on the battery.

You have encountered fixtures in other contexts before without knowing it. A race track is an example of fixture. The cars and drivers racing around it are different, but the pavement and curves are the same for everyone. When a race (which is essentially a benchmark test) pits the cars against each other, the fixtures are important in ensuring that the winner is meaningful. Everyone faces the same conditions, yet one car will be faster than the rest. If every car raced on a different course the race results would be meaningless. Sports and competitive events are filled with examples of fixtures—generally known as “having a level playing field.”
The idea is to fix the environment so that the environment will not skew the results.

