我正在学习 Michael Hartl 的 RoR 教程,它涵盖了密码加密的基础知识。这是当前的用户模型:
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email,: password, :password_confirmation
email_regex = /^[A-Za-z0-9._+-]+@[A-Za-z0-9._-]+\.[A-Za-z0-9._-]+[A-Za-z]$/
#tests for valid email addresses.
validates :name, :presence => true,
:length => {:maximum => 50}
validates :email, :presence => true,
:format => {:with => email_regex},
:uniqueness => {:case_sensitive => false}
validates :password, :presence => true,
:length => {:maximum => 20, :minimum => 6},
:confirmation => true
before_save :encrypt_password
private
def encrypt_password
@encrypted_password = encrypt(password)
end
def encrypt(string)
string
end
end
(显然这没有进行任何加密,因为加密方法并未真正实现,但这不是我的问题)
然后我写了下面的规范(根据教程):
require 'spec_helper'
describe User do
before(:each) do
@attr = { :name => "Example User", :email => "user@example.com",
:password => "abc123", :password_confirmation => "abc123"}
end
describe "password encryption" do
before(:each) do
@user = User.create!(@attr) # we are going to need a valid user in order
# for these tests to run.
end
it "should have an encrypted password attribute" do
@user.should respond_to(:encrypted_password)
end
it "should set the encrypted password upon user creation" do
@user.encrypted_password.should_not be_blank
end
end
end
这些测试中的第一个通过,但由于 @user.encrypted_password
为 nil,因此第二个测试失败。但我不明白为什么它是 nil,因为 encrypt_password
方法应该由 before_save
调用。我知道我一定遗漏了什么 - 有人可以解释一下吗?
最佳答案
encrypt_password 方法不正确,应该是:
def encrypt_password
self.encrypted_password = encrypt(password)
end
注意 self 的使用,它将正确设置用户对象的属性,而不是创建一个被遗忘的实例变量。
关于ruby - Rails——before_save 不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6325846/