【发布时间】: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