Failing rspec - has_password? - Ruby On Rails tutorial

When running a test against my User class, I’m getting failures on each
of the tests, but as far as i can tell everything should be correct.

====Failures======

Failures:

  1. User has_password? method should exist
    Failure/Error: @user.should respond_to(:has_password?)
    expected nil to respond to :has_password?

    ./spec/models/user_spec.rb:126:in `block (3 levels) in <top

(required)>’

  1. User has_password? method should return true if the passwords match
    Failure/Error: @user.has_password?(@attr[:password]).should be_true
    NoMethodError:
    undefined method `has_password?’ for nil:NilClass

    ./spec/models/user_spec.rb:130:in `block (3 levels) in <top

(required)>’

  1. User has_password? method should return false if the passwords
    don’t match
    Failure/Error: @user.has_password?(“invalid”).should be_false
    NoMethodError:
    undefined method `has_password?’ for nil:NilClass

    ./spec/models/user_spec.rb:134:in `block (3 levels) in <top

(required)>’

====User Spec=====

describe "has_password? method" do

  it "should exist" do
    @user.should respond_to(:has_password?)
  end

  it "should return true if the passwords match" do
    @user.has_password?(@attr[:password]).should be_true
  end

  it "should return false if the passwords don't match" do
    @user.has_password?("invalid").should be_false
  end
end

==User Class========

class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email, :password, :password_confirmation

email_regex = /\A[\w+-.]+@[a-z\d-.]+.[a-z]+\z/i

validates :name, :presence => true,
:length => { :maximum => 50 }
validates :email, :presence => true,
:format => { :with => email_regex },
:uniqueness => { :case_sensitive => false }

Automatically create the virtual attribute ‘password_confirmation’.

validates :password, :presence => true,
:confirmation => true,
:length => { :within => 6…40 }

before_save :encrypt_password

def has_password?(submitted_password)
encrypted_password == encrypt(submitted_password)
end

private

 def encrypt_password
   self.encrypted_password = encrypt(password)
 end

 def encrypt(string)
   string # Only a temporary implementation!
 end

end

Thanks,

Jason


jason
Sent with Sparrow (http://www.sparrowmailapp.com/?sig)

Jake, thank you for posting the answer, it save me a great deal of time.

in your user_spec.rb file.
make sure you have:

before(:each) do
@user = User.create!(@attr)
end

right after the following line:

describe “has_password? method” do

it’s missing from the code in the tutorial. you’ll see it’s part of
the password encryption block. it looks like it stubs out a user for
that test. it’s not very DRY…probably a way to have that stub block
run for each describe block, but that’s a bit further along than i
am. :slight_smile: hope it helps…got my tests working.

Jake, thanks for posting. It fixed my problem.