开发者

Rspec: Result matched using == but still gives "Failed" test result

Good day! I'm practising materials from "Ruby on Rails Tutorial" by Michael Hartle. Below is the failure message I received, even though the "expected" and "got" seems to match. Would you please give me some suggestion to see how I should approach this issue? Thank you so much!

Rspec: Result matched using == but still gives "Failed" test result

Below is the implementation code:

class User < ActiveRecord::Base
  attr_accessor :password
  attr_accessible :name, :emp_id, :dept_id, :password, :password_confirmation 
  validates :emp_id, :presence => true
  validates :name, :presence => true,
               :length => { :maximum => 50 }
  validates :password, :presence => true,
            :confirmation => true,
            :length => { :within => 6..40 }
  before_save :encrypt_password
  def has_password?(submitted_password)
    encrypted_password == encrypt(submitted_password)
  end
  def self.authenticate(emp_id, submitted_password)
    user = find_by_emp_id(emp_id)
    return nil if user.nil?
    return user if user.has_password?(submitted_password)
  end
  private 
    def encrypt_password
      self.salt = make_salt if new_record?
      self.encrypted_password = encrypt(password)
    end
    def encrypt(string)
      secure_hash("#{salt}--#{string}")
    end
    def make_salt
      secure_hash("#{Time.now.utc}--#{password}")
开发者_C百科    end
    def secure_hash(string)
      Digest::SHA2.hexdigest(string)
    end
end

Below is the SPEC code:

require 'spec_helper'
describe User do
  before(:each) do
    @attr = {:name=>"Example", :dept_id=>01, :emp_id=>10, :password=>"pwdabcd", :password_confirmation => "pwdabcd" }
  end
  .
  .
  .   
  describe "password encryption" do
    before(:each) do
      @user = User.create!(@attr)
    end
    .
    .
    . 
    describe "authenticate method" do
      it "should return the user on emp_id password match" do
        matching_user = User.authenticate(@attr[:emp_id], @attr[:password])
        matching_user.should == @user
      end
    end
  end
end

Thank you so much for your kind assistance. Have a nice day!


Kevin - when you see a failure message like that, the representation of the object (#<User ...>) is up to the object, so it's possible that it doesn't show you everything that is being compared by ==. My guess is it has something to do with :password_confirmation, but I'm not certain. It doesn't look like the implementation is using it yet, so try removing password_confirmation from @attr in the spec, and from the attr_accessible declaration, and see if it passes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜