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 scaffold. But of course you can also define your own files. All fixtures are loaded anew into the test database by default with every test.

Buy the new Rails 5.1 version of this book.

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

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: barak.obama
  last_name: Obama

two:
  login_name: george.w.bush
  last_name: Bush
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: barak.obama
  last_name: Obama
  birthday: <%= 20.years.ago.to_s(:db) %>

two:
  login_name: george.w.bush
  last_name: Bush
  birthday: <%= 20.years.ago.to_s(:db) %>

Thank you for your support and the visibility by linking to this website on Twitter and Facebook. That helps a lot!