Created
April 25, 2011 07:54
-
-
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?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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