2011-10-10 56 views
1

美好的一天!我正在練習Michael Hartle的「Ruby on Rails教程」中的材料。 下面是我收到的失敗消息,即使「預期」和「得到」似乎匹配。請給我一些建議,看看我應該如何處理這個問題? 非常感謝! enter image description hereRspec:使用==匹配的結果,但仍給出「失敗」測試結果

下面是實現代碼:

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}") 
    end 
    def secure_hash(string) 
     Digest::SHA2.hexdigest(string) 
    end 
end 

下面是SPEC代碼:

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 

非常感謝你的善意幫助。 祝您有美好的一天!

回答

2

Kevin - 當您看到類似的失敗消息時,對象的表示形式(#<User ...>)取決於對象,因此它可能不會顯示您正在通過==比較的所有內容。我的猜測是它與:password_confirmation有關,但我不確定。它看起來並沒有使用它,所以請嘗試從規格中的@attr中刪除password_confirmation,並從attr_accessible聲明中刪除它,看看它是否通過。

+0

親愛的大衛,非常感謝你的建議。我同意你的看法,它可能不會向我顯示通過==比較的所有內容。我將測試用例問題更改爲'matching_user.emp_id.should == @ user.emp_id',並且我能夠通過測試。再一次,真的很感謝你的答案=)。 –

相關問題