NameError: undefined local variable or method `digest' for #<User:0xe9d3d58>

NameError: undefined local variable or method `digest' for #<User:0xe9d3d58>

我的 user.rb 文件包含

class User < ActiveRecord::Base
  attr_accessor :remember_token
  before_save { self.email = email.downcase }
  validates :name,  presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, length: { maximum: 255 },
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
  has_secure_password
  validates :password, presence: true, length: { minimum: 6 }

  # 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

  # Returns a random token.
  def User.new_token
    SecureRandom.urlsafe_base64
  end

  # Remembers a user in the database for use in persistent sessions.
  def remember
    self.remember_token = User.new_token
    update_attribute(:remember_digest, User.digest(remember_token))
  end

   # Forgets a user.
  def forget
    update_attribute(:remember_digest, nil)
  end

  # Returns true if the given token matches the digest.
  def authenticated?(attribute, token)
    return false if digest.nil?**
    BCrypt::Password.new(digest).is_password?(token)
  end
end

User_test.rb [65 -67行]是:

    test "authenticated? should return false for a user with nil digest" do
    assert_not @user.authenticated?(:remember, '')
end

我收到错误

test_authenticated?_should_return_false_for_a_user_with_nil_digest#UserTest (0.84s) NameError: undefined local variable or method `digest' for

        app/models/user.rb:37:in `authenticated?'
        test/models/user_test.rb:66:in `block in <class:UserTest>'

digest是一个class方法,在实例方法中调用。

将您的 authenticated 方法更改为

def authenticated?(attribute, token)
    return false if remember_digest.nil?**
    BCrypt::Password.new(remember_digest).is_password?(token)
  end

或将您的 digest 方法更改为

 def digest(string)
    cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
                                                  BCrypt::Engine.cost
    BCrypt::Password.create(string, cost: cost)
  end