Monday, September 22, 2008

Rails with NO Fixtures?

I have a Rails project, and I created a Country model. I added the basic details of Norway to the countries.yml fixture.
norway:
 code: NO
 name: Norway
I added a unit test to make sure I could get Norway by it's country code, which is NO
def test_find_by_code
 assert_equal countries(:norway), Country.find_by_code('NO')
end
Agreed, I probably don't need a unit test for this, but this should have worked, but it was failing with the following message.
Country id: 318845244, code: "1", name: "Norway" expected but was
nil
Apparently NO in the yaml file is interpreted as a 0 (zero). To prove the theory I changed the code of norway to YES. The unit test failed, and indicated that the model it expected should have had code: "1". Changing countries.yml to be...
norway:
 code: "NO"
 name: Norway
I personally really like fixtures and the nice features they bring in, but sometimes they can catch you out. I'm sure it's not a bug, I've just never encountered this before. Ever found anything strange in your fixtures?

1 comment:

Rubyguy said...

I don't use fixtures for any of my projects. Finding the right fixtures to use for a particular unit test, making new fixtures and so forth is simply painful. So I started using factory_girl and it works like a charm.

Need a new User? Simply call Factory(:user). The users need unique names? Make a sequence. Factories brought me to testing heaven. You should try it out: http://github.com/thoughtbot/factory_girl/tree/master