Fixtures

Learn about fixtures, fixtures files, fixture entry, and YAML.

Rails has always made it easy to manage a database just for test data automatically cleared between tests. While there’s no denying this is tremendously useful, it has also pulled all of us into feeling that a test that touches the database (a huge third-party dependency) is somehow a unit test. One of the most valuable ways in which Ruby-on-Rails has supported automated testing is using easily created data accessible to all the tests in our system, no matter when or where we write those tests, using fixtures specified in a YAML file (YAML is a file format. The acronym stands for YAML Ain’t Markup Language). It’s sometimes hard for an experienced Rails programmer to remember just how exciting the YAML fixtures used to seem. We can just set up data once? In an easy format? And it’s always there? Amazing.

Over time, the infatuation with fixtures has dimmed, but they are still quick and easy to get data into our tests.

What’s a fixture?

Generically, a fixture is any known baseline state that can be made to exist at the beginning of a test. A fixed state’s existence makes it possible to write tests that make assumptions based on that particular set of data. In Rails, the term “fixture” refers to a specific mechanism baked into the framework to easily define a set of objects that will exist globally for all tests. These fixtures are defined in a set of YAML files that are automatically written to the database and converted to ActiveRecord objects at the beginning of each test run.

Fixture files directory

Each ...