views:

617

answers:

2

I'm reading about Rails fixtures in this guide (thanks, trevorturk). It appears you define classes in a Yaml file and they're automatically loaded into the test DB -- cool.

But if you want to specify that this recipe belongs to that cookbook (or whatever) how do you do that?

Are you supposed to specify the values for cookbook.id and recipe.cookbook_id by hand in the Yaml code? (Just a guess -- the guide doesn't show anything like that.) Or is there a more suitable way?

+11  A: 

You should use named fixtures, which automatically generate an id number for you where you don't provide one. These id numbers are essentially integer hashes of whatever string you use. Don't add the "_id" if you're referencing the named version:

# recipes.yml
chicken_soup:
  cookbook: my_recipes

# cookbooks.yml
my_recipes:
  title: My Test Cookbook
Andrew Vit
All right that actually worked. Thanks, man.
Ethan
Wow, that's much simpler than I thought it would be :) I was trying silly stuff like `client_id: <%= contacts(:dave).id %>` (which obviously doesn't work).
Skilldrick
+1  A: 

And if you want to DRY it up even more, check out the lite-fixtures plugin which lets you create blocks to avoid repeating properties shared between a group of fixtures.

Abie