Has_secure_password Bcrypt给出nil密码

问题描述 投票:2回答:1

我正在尝试跟随Michael Hartl的Ruby on Rail书,我在第10章,试图允许用户编辑他们的个人资料设置,这是最奇怪的错误--bcrypt的password_digest正在破坏我的测试。

users.yml里

user:
  name: Example User
  email: [email protected]
  password_digest: <%= User.digest("password") %>

当我在rails控制台中运行它时,这就是我所看到的

user.valid? =>假

user.errors.full_messages => [“密码不能为空”,“密码太短(最少6个字符)”]

user.rb

class User < ApplicationRecord
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
  before_save {
   self.email.downcase!
  }

  validates :name, presence: true, length: { maximum: 50 }
  validates :email, presence: true, length: { maximum: 255 },
            format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
  validates :password, presence: true, length: { minimum: 6 }
  has_secure_password

  # Returns the hash digest of the given string.
  def User.digest(string)
    cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
               BCrypt::Engine.cost
    BCrypt::Password.create(string, cost: cost)
  end
end

我正在使用bcrypt版本'3.1.11'

我的测试代码

 def setup
    @user = users(:marko)
  end

  test "successful edit" do
    log_in_as(@user)
    get edit_user_path(@user)
    name = "Foo bar"
    email = "[email protected]"
    patch user_path(@user), params: { user: {
                                          name: name,
                                          email: email,
                                          password: "password",
                                          password_confirmation: "password" } }
    assert_not flash.empty?
    assert_redirected_to @user
    follow_redirect!
    @user.reload
    assert_equal name, @user.name
    assert_equal email, @user.email
  end

什么想法可能是错的?

ruby-on-rails ruby bcrypt
1个回答
0
投票

尝试使用以下代码

user:
  name: Example User
  email: [email protected]
  password: "password"

Bcrypt确认password attr_accessor在创建新记录时应该存在(更新时可选)。

另外你应该将allow_blank: true添加到length validation以获取密码,因为当密码本身为空/零时不需要长度验证

© www.soinside.com 2019 - 2024. All rights reserved.