2013-02-22 179 views
2

我正在使用Hartl的Rails教程。我已经得到了第7章,但我的RSpec测试用例的一个出现故障,特别是一个涉及密码不匹配:Ruby on Rails教程(Hartl)第7.2.3章RSpec测试失败

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 

输出端子: 失败:

1) User password encryption has_password? method should be false if the passwords don't match 
Failure/Error: @user.has_password?("invalid").should be_false 
    expected "273725daa81e74764ea1e941a0789da7d580656cd321c64e39d1389f6a7e14d9" to be false 
# ./spec/models/user_spec.rb:111 

这里是我的/user.rb代码:

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

email_regex = /\A[\w+\-.][email protected][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 unless has_password? (password) 
     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 

我似乎无法弄清楚什么是错误的,我的生活。我感谢帮助!

回答

3

在你has_password?方法

encrypted_password = encrypt(submitted_password)需要阅读: encrypted_password == encrypt(submitted_password)

+1

你刚才打我的答案:-) – 2013-02-22 00:43:56

+0

哇哦。我想这就是我没有阅读字符的特点!谢谢! – 2013-02-22 00:50:29

相关问题