2011-11-11 119 views
2

我剛開始使用rails,並決定遵循M.Hartl的「Ruby on Rails Tutorial」。看起來像一個很好的介紹。密碼Ruby on Rails教程M. Hartl

我碰到一個失敗的測試這讓我瘋狂。 我正在軌3.1.1,與rspec的2.7.0

我曾嘗試修改情況,並測試了「has_password」方法的工作。

失敗的測試:

 
1) User password encryption authenticate method should return the user on email/password match 
Failure/Error: matching_user.should == @user 
expected: # 
     got: nil (using ==) 
# ./spec/models/user_spec.rb:149:in `block (4 levels) in ' 

RSpec的測試:

describe User do 

before(:each) do 
@attr = {:name => 'testing', 
     :email =>'[email protected]', 
     :password => "testtest", 
     :password_confirmation => "testtest"} 
end 

... 

describe "password encryption" do 
    before(:each) do 
    @user = User.create!(@attr) 
    end 

... 

describe "authenticate method" do 

    it "should exist" do 
    User.should respond_to(:authenticate) 
    end 

    it "should return nil on email/password mismatch" do 
    User.authenticate(@attr[:email], "wrongpass").should be_nil 
    end 

    it "should return nil for an email address with no user" do 
    User.authenticate("[email protected]", @attr[:password]).should be_nil 
    end 

    it "should return the user on email/password match" do 
    matching_user = User.authenticate(@attr[:email], @attr[:password]) 
    matching_user.should == @user 
    end  
end 

在用戶模式:

... 

def has_password?(submitted_password) 
    encrypt_password == encrypt(submitted_password) 
end 

def self.authenticate(email, submitted_password) 
    user = find_by_email(email) #self.where("email = ?", email) 
    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 

我想不出我在做什麼錯在這裏。

+0

這本書也有論壇,顯然。這也有幫助: http://getsatisfaction.com/railstutorial – Slamice

回答

1

在發生故障的規格必須

matching_user.should == @user 

@user因此它設置爲nil不被任何定義。

編輯:

嘗試添加以下puts到失敗規範,看看有什麼結果,你在你的規格輸出得到它運行後。

it "should return the user on email/password match" do 
    matching_user = User.authenticate(@attr[:email], @attr[:password]) 
    puts matching_user # add this 
    puts @user   # and also this 
    matching_user.should == @user 
end  
+0

謝謝,但我最初由於這篇文章的長度省略了創建用戶的代碼。我添加了它。仍是同樣的問題。 – Slamice

+0

謝謝!有了您的幫助調試,我發現我的has_password方法有一個錯字: '高清has_password(submitted_pa​​ssword) encrypted_pa​​ssword ==加密(submitted_pa​​ssword) end'? – Slamice

相關問題