7.3. Fixtures

With fixtures you can generate example data for tests. The default format for this is YAML. The files for this can be found in the directory test/fixtures/ and are automatically created with rails generate. But of course you can also define your own files. All fixtures are loaded anew into the test database by default with every test.[27]

Static Fixtures

The simplest variant for fixtures is static data. The fixture for User used in Section 7.2, “Example for a User in a Web Shop” statically looks as follows:
one:
  login_name: horst.meier
  last_name: Meier

two:
  login_name: emil.stein
  last_name: Stein
You simple write the data in YAML format into the corresponding file.

Fixtures with ERB

Static YAML fixtures are sometimes too unintelligent. In these cases, you can work with ERB (see the section called “Programming in an erb File”).
If we want to dynamically enter today's day 20 years ago for the birthdays, then we can simply do it with ERB in test/fixtures/users.yml
one:
  login_name: horst.meier
  last_name: Meier
  birthday: <%= 20.years.ago.to_s(:db) %>

two:
  login_name: emil.stein
  last_name: Stein
  birthday: <%= 20.years.ago.to_s(:db) %>


[27] Examples for alternative formats (e.g. CSV) can be found at http://api.rubyonrails.org/classes/ActiveRecord/Fixtures.html.

Updates about this book will be published on my Twitter feed.