【发布时间】:2021-04-10 03:05:18
【问题描述】:
我正在尝试跟随 Michael Hartl 的 Ruby on Rail 一书,我在第 10 章,尝试允许用户编辑他们的配置文件设置,这是最奇怪的错误 - bcrypt 的 password_digest 正在破坏我的测试。
users.yml
user:
name: Example User
email: example@gmail.com
password_digest: <%= User.digest("password") %>
当我在 Rails 控制台中运行它时,这就是我所看到的
user.valid? => false
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 = "foo@bar.com"
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
有什么想法可能是错的吗?
【问题讨论】:
-
尝试在 yml 中提供
password。摘要应该是自动创建的。 -
试过这个,我得到
ActiveRecord::Fixture::FixtureError: table "users" has no column named "password"。 -
你的测试代码怎么样?
-
将我的测试代码添加到问题中,尽管我能够在控制台中复制问题
-
好的,所以我决定不做一些完全不相关的事情就继续前进。由于某些莫名其妙的原因-测试自行修复。虽然这是有道理的,因为我在互联网上找到的任何东西都没有困扰我的代码,但我很犹豫,因为问题是随机出现的。 TL;DR-这个问题没有答案。目前,问题已解决。
标签: ruby-on-rails ruby bcrypt