This has been kicking my butt all morning.
Right now, I'm just beginning Chapter 7.2.4 of Michael Hartl's excellent Ruby on Rails 3 Tutorial, and I'm running into some issues. The section begins with a quick check of the has_password?
method, in the Rails console sandbox. Here's what I've typed in:
ruby-1.9.2-p180 :001 > User
=> User(id: integer, name: string, email: string, created_at: datetime, updated
updated_at: datetime, encrypted_password: string, salt: string)
ruby-1.9.2-p180 :002 > User.create(:name => "John Pavlick", :email => "jmpavlick
@gmail.com", :password => "foobar", :password_confirmation => "foobar")
=> #<User id: nil, name: "John Pavlick", email: "jmpavlick@gmail.com", created_
at: nil, updated_at: nil, encrypted_password: nil, salt: nil>
ruby-1.9.2-p180 :003 > user = User.find_by_email("jmpavlick@gmail.com"
ruby-1.9.2-p180 :004?> )
=> #<User id: 1, name: "John Pavlick", email: "jmpavlick@gmail.com", created_at
: "2011-04-15 15:11:46", updated_at: "2011-04-15 15:11:46", encrypted_password:
nil, salt: nil>
ruby-1.9.2-p180 :005 > user.has_password?("foobar")
=> false
This should be returning true
.
Here's my user.rb
model:
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email, :password, :password_confirmation
email_regex = /^[\w+\-.]+@[a-z\d\-.]+\.[a-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
# Return true if the user's password matches the submitted 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
All of my RSpec
tests pass perfectly, and as far as I can tell, I've coded in verbatim everything in the book - I've even copy/pasted some code to make sure. I don't see any reason at all for this to be failing, so any help will be a lifesaver.
Here's a link to the book, online: [link]