[Rails] Unit test failure - nil object?

Lindsay Boyd
Wed, 22 Feb 2006 12:32:08 -0000

I''m following instructions in the Agile book, page 146 for testing an
object update to the database. Here''s my code:

  def test_update
    assert_equal "jack@smiths.com", @user.email
    @user.email = "jack@smiths.org"
    assert @user.save, @user.errors.full_messages.join("; ")
    @user.reload
    assert_equal @user.email, "lindsay.boyd@ntlworld.co.uk"
  end

An error is generated when the save method is called. I''m guessing the
code is OK and the problem lies with the database? Here''s the error
text:

  1) Error:
test_update(UserTest):
NoMethodError: You have a nil object when you didn''t expect it!
You might have expected an instance of Array.
The error occured while evaluating nil.+

/usr/local/lib/ruby/gems/1.8/gems/activerecord-1.13.2/lib/active_record/locking.rb:33:in
`update_without_callbacks''

/usr/local/lib/ruby/gems/1.8/gems/activerecord-1.13.2/lib/active_record/callbacks.rb:274:in
`update_without_timestamps''

/usr/local/lib/ruby/gems/1.8/gems/activerecord-1.13.2/lib/active_record/timestamp.rb:39:in
`update''

/usr/local/lib/ruby/gems/1.8/gems/activerecord-1.13.2/lib/active_record/base.rb:1431:in
`create_or_update_without_callbacks''

/usr/local/lib/ruby/gems/1.8/gems/activerecord-1.13.2/lib/active_record/callbacks.rb:249:in
`create_or_update''

/usr/local/lib/ruby/gems/1.8/gems/activerecord-1.13.2/lib/active_record/base.rb:1226:in
`save_without_validation''

/usr/local/lib/ruby/gems/1.8/gems/activerecord-1.13.2/lib/active_record/validations.rb:698:in
`save_without_transactions''

/usr/local/lib/ruby/gems/1.8/gems/activerecord-1.13.2/lib/active_record/transactions.rb:126:in
`save''

/usr/local/lib/ruby/gems/1.8/gems/activerecord-1.13.2/lib/active_record/connection_adapters/abstract/database_statements.rb:51:in
`transaction''

/usr/local/lib/ruby/gems/1.8/gems/activerecord-1.13.2/lib/active_record/transactions.rb:91:in
`transaction''

/usr/local/lib/ruby/gems/1.8/gems/activerecord-1.13.2/lib/active_record/transactions.rb:118:in
`transaction''

/usr/local/lib/ruby/gems/1.8/gems/activerecord-1.13.2/lib/active_record/transactions.rb:126:in
`save''
    test/unit/user_test.rb:31:in `test_update''

2 tests, 16 assertions, 0 failures, 1 errors