views:

194

answers:

1

When creating an ActiveRecord in rspec, I use fixtures for valid records. But when using the fxitures in tests, they seem to fail validation. In the following example, the employee seems to be perfectly valid, and yet the associated validation in the spec says they are invalid.

class Employee < ActiveRecord::Base
  validates_presence_of     :email
end

class User < ActiveRecord::Base
  validates_associated      :employee
end

#Command line debugger in 'debugger' (below) returns:
Employee.find(745185059).errors.count         # => 0
Employee.find(745185059).errors.full_messages # => []
Employee.find(745185059).valid?               # => true

For Example:

describe SessionsController do
  fixtures :users, :employees

  describe "Logging in by cookie" do
    def set_remember_token token, time
      @user[:remember_token]            = token; 
      @user[:remember_token_expires_at] = time
      debugger
      @user.save! # THIS SAYS THE EMPLOYEE IS INVALID, but why, if the fixtures are good?
    end    
    it 'logs in with cookie' do
      stub!(:cookies).and_return({ :auth_token => 'hello!' })
      logged_in?.should be_true
    end
  end
end

Any ideas why I get the validation failure? (Of course, I cut out a lot of the middle code, it's possible that the error is somewhere else entirely)

+1  A: 

You could debug the @user after a .save (without the bang!), that should add the errors, it might be caused by a model callback or maybe something that your validate method does. In your test, just do:

@user.save
puts @user.errors.inspect # or your command line debugger

and read the output when running your test.

Omar Qureshi
That did the trick! I didn't know that even trying Employee(123).send(validate)would not work. Thanks a bunch for your time, Omar!
btelles