Topic: has_and_belongs_to_many fixtures

Hi Im just wondering how I would use fixtures to setup my test database with has_and_belongs_to_many relationships?

Re: has_and_belongs_to_many fixtures

Let's say you have three tables: contacts, cities, and contacts_cities.

cities has_and_belongs_to_many contacts.

class CityTest < Test::Unit::TestCase
  fixtures :cities, :contacts
 
  def test_truth
    assert true
  end
end

To link a city to a contact before running an assertion, you'd just have something like this in your test method:
@city.contacts << contacts(:stan)

vinnie - rails forum admin

Re: has_and_belongs_to_many fixtures

alistair wrote:

Hi Im just wondering how I would use fixtures to setup my test database with has_and_belongs_to_many relationships?

If you want tableA_tableB fixutes, you can just make them by hand. Not sure if there is a magic way to do that, or if such a magic way would even be a good idea. Fixtures are pretty simple, data just gets shoved into corresponding columns.

Something like:
File: authors_books.yml
example one:
  author: 1
  book: 1

Re: has_and_belongs_to_many fixtures

I believe that will only work if you have actually created a model object for the join (or at least that was the impression I got from reading other forum.  If I get a chance i'll test it out and post back the results.

Re: has_and_belongs_to_many fixtures

This is how I've done it in the past, and it has worked. Let's say you have 3 tables: users, roles_users, roles. You need to create a fixture for each table wether or not they have an associated model. So, you should have users.yml, roles_users.yml, and roles.yml. Here's an example of the users_roles.yml

first:
  role_id: 1
  user_id: 1
second:
  role_id: 2
  user_id: 1

Then you load all of the fixtures in you test like this:

fixtures :roles, :roles_users, :users

That's all there is too it.

Railscasts - Free Ruby on Rails Screencasts