Foxy Fixtures Explained

As of October, 2006, Rails integrated a plugin called Foxy Fixtures into the core API.

This makes it easier to write fixtures–no more worrying about IDs! What’s more, created_on and updated_on are automatically populated with today’s date! Instead of writing this:


# libraries.yaml
central_library:
id: 1
city: "Toronto"
created_on: <%= Date::today %>

You can write this:
# libraries.yaml
central_library:
city: “Toronto”

Nice, eh? Even better--if you have a multiplicity association (has_many, belongs_to, or has_and_belongs_to_many), your fixture goes from:


# books.yaml
agile_rails:
title: "Agile Web Development with Rails"
published: 2007
library_id: 1

To:


# books.yaml
agile_rails:
title: "Agile Web Development with Rails"
published: 2007
library: central_library

Notice how much more readable and maintainable it is! No more IDs polluting your fixtures, no more worries about putting the right or wrong ID; but simple, easy-to-use names.

Now, if you try this, out-of-the-box, it might not work--there's a tricky gotcha--all the IDs have changed.

You might have assumed, from the example, that with Foxy Fixtures, central_library has an ID of one.

You'd be wrong if you thought that.

What is the ID? If you look through the test log, you'll see something like this:


...
Library Load (0.000000) SELECT * FROM `libraries` WHERE (`libraries`.`id` = 9523826)
...

What does that mean? It means, quite simply, that the IDs are assigned through some mechanism out of our control--that you cannot depend on the IDs being anything. (The IDs are not completely random, though; the same fixture will always have the same ID.) The good news is, you don't really care what the ID is--because you can reference the fixture by name!

And that's fixtures in a nutshell. So take a few minutes now to modify your Rails fixtures to take advantage of this--the ease (and maintainability) of Foxy Fixtures over regular ol' fixtures makes it an outstanding addition to the core Rails API.

About Ashiq Alibhai

Ashiq Alibhai, PMP, has been a Rails aficionado since 2007, and developed web applications since early 2003, where he learned PHP in one summer. As the driving-force behind RailsRocket and the Launchpad project, he seeks to share the ease of development with Rails far and wide.
This entry was posted in Gems and Plugins, Testing and tagged , , . Bookmark the permalink.

One Response to Foxy Fixtures Explained

  1. grosser says:

    I also used this, but its somewhat the same pain to maintain/remember where each set of fixtures is kept/whats special about it,
    another approach, that does not require ‘even more fixtures’ can be found @ http://github.com/grosser/valid_attributes/tree/master