【问题标题】:Password can't be blank, bcrypt on user minitest, rails 6密码不能为空,用户 minitest 上的 bcrypt,rails 6
【发布时间】:2021-07-06 08:09:33
【问题描述】:

当我尝试在 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>'

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

感谢您的帮助!

【问题讨论】:

  • 你也可以发布用户模型的架构吗?
  • @Mshka 我刚刚添加了它,谢谢!
  • 请注意,您可能也不想在夹具中设置用户 ID。它可能会导致与现有用户的冲突。让数据库设置ID。

标签: ruby-on-rails bcrypt minitest


【解决方案1】:

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

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

【讨论】:

【解决方案2】:

在得到上述建议后,在followingquestions 的部分帮助下设法解决了这个问题,并在has_secure_password. 上进一步阅读感谢 Schwern 和 Mshka!

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

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

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

我将测试更新为:

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

这会验证fixture,然后确保身份验证返回一个用户(成功)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-04
    • 2017-12-07
    • 2015-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多