Ruby on Rails
HowToUseFixturesWithHABTM

If you need to test an application that uses a has_and_belongs_to_many (habtm) relationship, you’ll need to do a few extra things to your testing setup. Since it took me a bit of poking to 1. figure out that the habtm relationship wasn’t happening automagically in the tests, and 2. figure out how to make it happen, I thought I would jot down a few notes that may help others.

To test your habtm relationship, you’ll need to create an extra fixture file in your fixtures directory to represent the join table. The fixture should be named the same as the join table for your habtm relationship. The fixture should look something like this.

Example YAML Fixture

File name: categories_posts.yml


association1:
  post_id: 1
  category_id: 2
association2:
  post_id: 2
  category_id: 2
association3:
  post_id: 2
  category_id: 1

In your functional test

You’ll also need to include all three fixtures at the beginning of your functional test:


fixtures :posts, :categories, :categories_posts

Don’t forget to include fixtures for models on both ends of HABTM association (posts and categories in the example above).

There was a brief discussion of this on the mailing list. If other documentation about this exists, please add a reference to it on this page.

Alternately, some find it easier to us CSV fixtures for habtm relationship since you can drop the repeated information. Using CSV, the previous example would look like:

Example CSV Fixture

File name: categories_posts.csv


post_id, category_id
1, 2
2, 2
2, 1

Resources

category: Howto