【发布时间】:2014-06-21 02:52:37
【问题描述】:
我正在学习使用 Rails 4 和 rspec 的 TDD。我为我的用户模型制作了一些测试用例来检查密码长度。到目前为止,我有两个测试来检查用户输入的密码是否太短,一个是密码在 6 到 10 个字符之间。
到目前为止,“密码太短”测试通过了:
it "validation says password too short if password is less than 6 characters" do
short_password = User.create(email: "tester@gmail.com", password: "12345")
expect(short_password).not_to be_valid
end
但是,在我确实有有效密码的测试中,它失败了:
it "validation allows passwords larger than 6 and less than 10" do
good_password = User.create(email: "tester2@gmail.com", password: "blahblah")
expect(good_password).to be_valid
end
我得到这个错误:
Failure/Error: expect(good_password).to be_valid
expected #<User id: 1, email: "tester2@gmail.com",
created_at: "2014-06-21 02:43:42", updated_at: "2014-06-21 02:43:42",
password_digest: nil, password: nil, password_hash: "$2a$10$7u0xdDEcc6KJcAi32LBW7uzV9n7xYbfOhZWdcOnU5Cdm...",
password_salt: "$2a$10$7u0xdDEcc6KJcAi32LBW7u"> to be valid,
but got errors: Password can't be blank, Password is too short (minimum is 6 characters)
# ./spec/models/user_spec.rb:12:in `block (3 levels) in <top (required)>'
编辑:这是我的模型代码:
class User < ActiveRecord::Base
has_many :pets, dependent: :destroy
accepts_nested_attributes_for :pets, :allow_destroy => true
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: true
validates :password, presence: true, :length => 6..10, :confirmation => true
#callbacks
before_save :encrypt_password
after_save :clear_password
#method to authenticate the user and password
def self.authenticate(email, password)
user = find_by_email(email)
if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
user
else
nil
end
end
#method to encrypt password
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
#clears password
def clear_password
self.password = nil
end
end
我对为什么创建测试对象时密码为 nil 感到困惑。
谢谢!
【问题讨论】:
-
您的模型必须有一些影响密码计算方式的回调。这表明
password_hash和password_salt正在填充。你能显示你的型号代码吗?
标签: ruby-on-rails rspec