Setting Up a Test Database with Fixtures
Automated testing needs a stable database environment in which to do its work. The contents of the development database will—and should—change on a regular basis as you tinker, try things out, and experiment to see just how well everything works. This is wonderful for a human development process, but that level of change is dreadful when a computer is testing an application. Once the testing framework is told which value to check for, it can’t choose another value because it knows someone else was playing with the data. In fact, if previous tests change the data, the order in which tests are conducted could itself become an issue, masking some bugs and falsely reporting others.
Rails provides this stable environment two ways. First, as noted earlier, it maintains a separate test environment, complete with its own database. Second, the testing environment expects that developers will define stable data, called fixtures, for use in that database. Every time a new test is run, the database is reset to that stable set of data. It’s a slow way to do things, but it’s extremely reliable.
Fixtures are written in YAML. You don’t need to know much about YAML to use and create them, however. Rails, in fact, has been creating fixtures along with scaffolding all along. If you check the test/fixtures directory of the courses and students application, you’ll see files named awards.yml, courses.yml, and students.yml. Their contents aren’t particularly exciting, ...
Get Learning Rails: Live Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.