I have some players and the players have a trade state. Rather than hard code trade states like "active" and "inactive" and then have to go looking for strings, I thought I'd be clever and have a separate TradeState model so that a Player has a trade_state_id (a Player can be in only one trade state at a time).
Now, it would be a convenience to be able to get all the active players by using named scopes and then by saying "Player.active". To do that, I need to get the ID of the TradeState records that matches 'active', so I came up with this in the Player class:
named_scope :active, :conditions => {:trade_state_id => TradeState.active.first.id}
This works like a charm when tested in script/console, but it does not work when I go to test. I'm using RSpec, but I suspect that isn't pertinent. When I run the most trivial test, I get the following error:
"Called id for nil, which would mistakenly be 4"
As far as I can tell, the testing framework is loading and parsing the models in alphabetical order. The framework parses the named_scope call in the Player model and dutifully goes to look up the id for the first TradeState record that is active. However, that model hasn't been processed yet and isn't ready, hence the error about getting the id of nil.
At first I thought it was because there may not have been any records in the trade_states table, so I create and save the trade_states that I needed in the before(:each) block, but that didn't work. So then I made some fixtures and tried loading them, but that didn't work.
Does this seem plausible? Are there other explanations? How about work arounds? I could try mocking the TradeState object and I'll give that a go.
Thanks so very much for your time.