未定义包装器方法



我很难理解为什么我不能成功地在我的User模型中调用包装器方法。我的问题在于下面所示的encrypt_password方法中的self.password_hash = hash_check(password, password_salt)行。我的hash_check方法在身份验证方法中正常工作,所以我有点困惑。当我运行测试时,我得到错误undefined method 'hash_check' for #<User:0x007f94851a5f88>

class User < ActiveRecord::Base
  attr_accessor :password
  before_save :encrypt_password
  validates_confirmation_of :password
  validates_presence_of :password, :on => :create
  validates_presence_of :email
  validates_uniqueness_of :email
  def encrypt_password
    if password.present?
      self.password_salt = generate_salt
      self.password_hash = hash_check(password, password_salt)
    end
  end
  def self.authenticate(email, password)
    user = find_user(email)
    user && user.password_hash == hash_check(password, user.password_salt) ? user : nil
  end
  def self.find_user(email)
    user = find_by_email(email)
  end
  private
  def self.hash_check(password, password_salt)
    BCrypt::Engine.hash_secret(password, password_salt)
  end
  def generate_salt
    BCrypt::Engine.generate_salt
  end
end
require 'spec_helper'
describe 'User' do
  let(:user) { User.create(email: 'user@gmail.com', password: "secure_password") }
  it 'creates a user object' do
    user.should be_kind_of User
  end
  describe '.find_user' do
    let(:valid_user_search) { User.find_user('user@gmail.com') }
    let(:invalid_user_search) { User.find_user('notregistered@gmail.com') }
    it 'returns a user by their email' do
      user.should == valid_user_search
    end
    it 'return nil if no user if found' do
      invalid_user_search.should == nil
    end
  end
  describe '.authenticate' do
    let(:auth_user) { User.authenticate(user.email, user.password) }
    let(:non_auth_user) { User.authenticate('notregistered@gmail.com', 'invalidpass') }
    it 'returns an valid user' do
      auth_user.should == user
    end
    it 'returns nil on an invalid user' do
      non_auth_user.should == nil
    end
  end
  describe '.encrypt_password' do
    it 'returns a password salt'
    it 'return a password hash'
  end
end

self.hash_check是一个类方法(因为你放了self)。它在self.authenticate中工作,因为它也是一个类方法(因为它不依赖于实例)。然而,它不会在实例方法上工作,如encrypt_password,因为你根本没有调用类方法。

因此,您需要将实例方法中的hash_check(password, password_salt)替换为self.class.hash_check(password, password_salt)User.hash_check(password, password_salt)以便能够使用类方法

点击这里了解更多细节

最新更新