NameError:未定义的局部变量或## user:0xe9d3d58>的方法`digest'

时间:2015-11-16 13:44:48

标签: ruby-on-rails error-handling railstutorial.org

我的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:未定义的局部变量或方法`digest'for

     

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

1 个答案:

答案 0 :(得分:0)

$http是一个类方法,它在实例方法中调用。

digest方法更改为

authenticated

或将def authenticated?(attribute, token) return false if remember_digest.nil?** BCrypt::Password.new(remember_digest).is_password?(token) end 方法更改为

digest