SpicyCode

The ramblings of Chad Humphries

Posts Tagged ‘fixtures

Fixtures, a 22 part retrospective

Ok, so it’s just one part and you are most of the way through the first paragraph already. Tricky, eh?

Recently while dumpster diving in the activerecord source I ran across the fixtures documentation. I picked it up, cleaned it off and read through it. In the end I came across some alternate ways of using fixtures I hadn’t heard about.

From the documentation:

Fixtures are a way of organizing data that you want to test against; in short, sample data. They come in 3 flavours: YAML fixtures, CSV fixtures, and Single-file fixtures.

YAML fixtures

Everyone knows our old friend YAML. A new trick for me was the concept of ordered YAML files (see the specification). These can come in handy if you have foreign key constraints in play on the same table. An example follows.

--- !omap
  - parent:
     id:         1
     parent_id:  NULL
     title:      Parent
     - child:
        id:         2
        parent_id:  1
        title:      Child

CSV fixtures

Most are familiar with CSV and even CSV fixtures. A useful tidbit for me was the following:

Another unique attribute of the CSV fixture is that it has no fixture name like the other two formats. Instead, the fixture names are automatically generated by deriving the class name of the fixture file and adding an incrementing number to the end. For example the 1st fixture would be called “fixture_name_1” and the 2nd one would be called “fixture_name_2”.

Single-file fixtures (deprecated, but still hanging around)

Straight from the docs:

This type of fixtures was the original format for Active Record that has since been deprecated in favor of the YAML and CSV formats. Fixtures for this format are created by placing text files in a sub-directory (with the name of the model) to the directory appointed by Test::Unit::TestCase.fixture_path=(path) (this is automatically configured for Rails, so you can just put your files in /test/fixtures//—like /test/fixtures/web_sites/ for the WebSite model).

Each file can contain only one fixture record. They generally do not have a file extension as well. There contents are kept in name => value format; one pair to a row.

A sample directory structure:

  web_sites/google
  web_sites/yahoo.txt
  web_sites/ruby-on-rails

Conclusions?

I definitely enjoy the single file format in instances where you have something specific you want to test, although newer alternate ways of loading focused fixtures easily replace it. Nothing like a good journey through code, eh?

Advertisements

Written by spicycode

December 25, 2006 at 6:28 pm

Posted in programming

Tagged with , ,