views:

204

answers:

2

In the documentation concerning Fixtures (http://api.rubyonrails.org/classes/Fixtures.html) they provide the following example of using label references for associations:

### in pirates.yml
reginald:
  name: Reginald the Pirate
  monkey: george

### in monkeys.yml
george:
  name: George the Monkey
  pirate: reginald

So following their lead, I have a User model that has_one :profile, a Profile model that belongs_to :user, and tried to set up fixtures per their example:

### in users.yml
reginald:
  id: 1
  login: reginald

### in profiles.yml
reginalds_profile:
  id: 1
  name: Reginald the Pirate
  user: reginald

(Note: since my association is one-way, the User fixture doesn't have a "profile: reginalds_profile" association--putting it in causes an error because the SQL table has no profile_id attribute.)

The problem is, in my unit tests everything seems to load correctly, but users(:reginald).profile is always nil. What am I missing?

+1  A: 

You may have to declare that you're loading all of these fixtures as I do not believe the fixture loader follows associations like this automatically. In some cases you may have to do more than simply:

fixtures :all

Actually declaring each of them:

fixtures :users, :profiles
tadman
I think that is the case for integration tests, but for unit tests it seems to be loading all of my fixtures, just not making the association. I tried making them explicit and same problem.
MikeJ
The other thing to look at is if assigning ID values manually conflicts with the auto-assigment, cross-referencing feature.
tadman
I did some more searching and you are correct... see below.
MikeJ
+1  A: 

Based on tadman's suggestion I did some more searching and found the answer elsewhere on this site, so I might as well post it.

See post titled Automatic associations in ruby on rails fixtures

Apparently the way Rails finds associated fixtures when you use labels (user: reginald) instead of IDs (user_id: 1) is by hashing the name and assuming the hash is the ID. If you set the ID to something specific, this fails. But if you let Rails automatically assign IDs it uses that hashing scheme. So the documentation for fixture association labels is missing a key tidbit--if you are using labels you must avoid applying your own IDs in the fixtures to be matched. Fixtures not being matched by labels can still have whatever ID scheme you choose.

MikeJ
Thanks for doing the research here. I didn't know for sure as I try not to mix and match styles.
tadman