Accessing fixtures from unit tests


#1

I have set up some fixtures in test/fixtures/users.xml:

Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html

admin:
id: 1
username: admin
password: admin
pbarry:
id: 2
username: pbarry

I have a unit test for my user model:

require File.dirname(FILE) + ‘/…/test_helper’

class UserTest < Test::Unit::TestCase
fixtures :users

def test_find
user = User.find(@admin.id)
assert_equals(@admin.id,user.id)
end

end

When I run the test, I get this:

C:\ruby\workspace\lms>ruby test/unit/user_test.rb
Loaded suite test/unit/user_test
Started
E
Finished in 0.156 seconds.

  1. Error:
    test_find(UserTest):
    RuntimeError: Called id for nil, which would mistakenly be 4 – if you
    really wanted the id of nil, use object_id
    test/unit/user_test.rb:7:in `test_find’

1 tests, 0 assertions, 0 failures, 1 errors

Why is @admin nil? Shouldn’t it be populated from the fixture?


#2

Hello Paul,

2006/4/28, Paul B. removed_email_address@domain.invalid:
[…]

def test_find
user = User.find(@admin.id)
assert_equals(@admin.id,user.id)
end

end

[…]

Why is @admin nil? Shouldn’t it be populated from the fixture?

Because the instantiated fixtures are disabled by default.
You shoud use sth like :

admin = users(:admin)
user = User.find(admin.id)
assert_equals admin.id, user.id

 -- Jean-François.

#3

Thanks, that did it. This must be one of those new to Rails 1.1 things?
We
desparately need a new version of Agile Web Dev with Rails updated for
1.1.
I know the plan was to not “break the book”, but I think there a number
of
these little details that have unfortunately done that.