Ruby on rails RubyonRails教程(Hartl)第7.2.3章RSpec测试失败
我正在学习Hartl的Rails教程。我已经读到了第7章,但是我的一个RSpec测试用例失败了,特别是处理不匹配密码的那一个:Ruby on rails RubyonRails教程(Hartl)第7.2.3章RSpec测试失败,ruby-on-rails,ruby,Ruby On Rails,Ruby,我正在学习Hartl的Rails教程。我已经读到了第7章,但是我的一个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
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+\-.]+@[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
需要“摘要”
类用户true,
:length=>{:max=>50}
验证:email,:presence=>true,
:format=>{:with=>email_regex},
:唯一性=>{:区分大小写=>false}
验证:password,:presence=>true,
:confirmation=>true,
:length=>{:within=>6..40}
保存前:加密密码
def有密码吗?(已提交密码)
加密密码=加密(已提交密码)
结束
私有的
def加密密码
self.salt=make_salt,除非有密码?(密码)
self.encrypted_password=加密(密码)
结束
def加密(字符串)
安全散列(“#{salt}--#{string}”)
结束
def制盐
安全散列(“#{Time.now.utc}--#{password}”)
结束
def secure_散列(字符串)
摘要::SHA2.hexdigest(字符串)
结束
结束
我似乎不知道我这辈子到底出了什么问题。我感谢你的帮助 在您的
中是否有密码?
方法
encrypted\u password=encrypt(提交的密码)
需要阅读:
encrypted\u password==encrypt(submitted\u password)
你刚刚击败了我,答案是:-)哦,哇。我想这就是我没有逐字阅读的结果!谢谢