Skip to content

Instantly share code, notes, and snippets.

@AndrewTerry
Created April 25, 2011 07:54
Show Gist options
  • Save AndrewTerry/940262 to your computer and use it in GitHub Desktop.
Save AndrewTerry/940262 to your computer and use it in GitHub Desktop.
Why do I get "undefined method 'has_password?' for nil:NilClass" when I run my test?
require 'digest'
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 }
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.salt = make_salt if new_record?
self.encrypted_password = encrypt(password)
end
def encrypt(string)
secure_hash("#{salt}--#{string}")
end
def make_salt
secure_hash("#{Time.now.utc}--#{password}")
end
def secure_hash(string)
Digest::SHA2.hexdigest(string)
end
end
describe "has_password? method" do
it "should be true if the passwords match" do
@user.has_password?(@attr[:password]).should be_true
end
it "should be false if the passwords don't match" do
@user.has_password?("invalid").should be_false
end
end
@AndrewTerry
Copy link
Author

Thanks, aliavni - that's just what I was looking for!

@yuxili
Copy link

yuxili commented Jun 15, 2012

If you are following the Tutorial book (I think so),
it works if the test is within the following:

describe "password encryption" do
before(:each) do
@user = User.create!(@attr)
end
...
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment