密码不能为空,bcrypt on user minitest, rails 6

Password can't be blank, bcrypt on user minitest, rails 6

当我尝试在 Rails 6 中验证使用 bcrypt 和 has_secure_password 的用户模型时,我的有效用户夹具验证导致错误。

架构部分:

  create_table "users", force: :cascade do |t|
    t.string "first_name"
    t.string "last_name"
    t.string "email"
    t.string "password"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.string "password_digest"
  end

型号:

class User < ApplicationRecord
    has_many :organizations
    has_many :posts
    has_many :messages
    has_secure_password

    validates :first_name, presence: true 
    validates :last_name, presence: true
    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
    validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
    validates :password, presence: true, length: { minimum: 6 }

end

夹具:

valid_user:
  id: 4
  first_name: A
  last_name: User
  email: user@gmail.com
  password_digest: <%= BCrypt::Password.create('password') %>

测试:

test 'valid user' do
  users(:valid_user).save!
  assert users(:valid_user).valid?
end

错误:

ERROR["test_valid_user", #<Minitest::Reporters::Suite:0x00007f8dac077ce0 @name="UserTest">, 1.0667385000000422]
 test_valid_user#UserTest (1.07s)
ActiveRecord::RecordInvalid:         ActiveRecord::RecordInvalid: Validation failed: Password can't be blank, Password is too short (minimum is 6 characters)
            test/models/user_test.rb:18:in `block in <class:UserTest>'

我添加了 bang 以查看它为什么无效,我设置的密码既不能太短也不能为空。无论是添加密码夹具属性并手动将其设置为“密码”,还是尝试摘要,似乎都不起作用。

感谢您的帮助!

您需要设置 password 而不是 password_digest,因为您的验证确保您的密码存在,然后它可能会对其进行加密并将其存储在摘要字段中

valid_user:
  id: 4
  first_name: A
  last_name: User
  email: user@gmail.com
  password: password

following after getting the above suggestions, as well as reading further on has_secure_password. 的部分帮助下设法解决了这个问题,谢谢 Schwern 和 Mshka!

我的最后一个夹具验证需要更新为:

validates :password, length: { minimum: 6 }, allow_nil: true

要启用密码长度验证但允许空白密码,因为 has_secure_password 已经处理密码 validation/existence 一旦设置,所以仔细检查 nil 是 unnecessary/didn 不考虑它自己的密码处理验证。

我将测试更新为:

test 'valid user' do
  assert users(:valid_user).valid?
  assert_instance_of User, users(:valid_user).authenticate("password")
end

验证夹具,然后确保身份验证 returns 用户(成功)。