2009-07-14 73 views
0

- 前言:如果你想要忽略。
我是新來的rails,並且正在開發一個需要用戶認證的項目。 我發現this tutorial,並試圖通過它並瞭解發生了什麼。當然,這不完全是我現在需要的,所以我一直在進行修改。該教程在某些領域也過時了,所以我必須更新我的代碼。所以我的問題的一部分是,我不確定錯誤是在我的修改中,還是某些已被棄用的函數或什麼。控制器測試失敗的導軌用戶認證

- 問題
這是失敗的(最簡單的)測試。 (「預期不無」第一斷言語句。)

def test_authentication 
    #check we can log in 
    post :login, :user => { :username => "bob", :password => "test" } 
    assert_not_nil session[:user_id] 
    assert_equal users(:bob).id, session[:user_id] 
    assert_response :redirect 
    assert_redirected_to :action => 'welcome' 
end 

它調用user_controller動作登錄:

def login 
    if request.post? 
    if session[:user_id] = User.authenticate(params[:user][:username], params[:user][:password]) 
    flash[:message] = "Login succeeded!" 
    redirect_to_stored 
    else 
     flash[:warning] = "Login failed." 
    end 
    end 
end 

它調用用戶的方法驗證。我知道,身份驗證工作正常,但是,因爲我有一個單一的測試,它通過:

def test_registration 
    #check that we can register and are logged in automatically 
    post :register, :user => { :username => "newuser", :password => "pass", :password_confirmation => "pass", :email => "[email protected]" } 
    assert_response :redirect 
    assert_not_nil session[:user_id] 
    assert_redirected_to :action => 'welcome' 
end 

它調用user_controller動作暫存器

def register 
    @user = User.new(params[:user]) 
    if request.post? 
    if @user.save 
     session[:user_id] = User.authenticate(@user.username, @user.password) 
     flash[:message] = "Registration succeeded" 
     redirect_to :action => 'welcome' 
    end 
    else 
    flash[:warning] = "Registration failed" 
    end 
end 

成功地調用驗證。

用戶燈具有一個相應的記錄:

bob: 
    username: bob 
    email: [email protected] 
    hashed_password: 77a0d943cdbace52716a9ef9fae12e45e2788d39 # test 
    salt: 1000 

我測試過的哈希密碼和鹽 - 「測試」是正確的密碼。

因此,通過我的分析,錯誤一定是在3個地方之一:
我怎麼送我的職務的請求,
我如何訪問在登錄操作的參數,
或一些夾具加載方面。 (最初我使用教程的代碼顯式加載燈具(self.use_instantiated_fixtures = true;燈具:用戶),但我讀過所有的燈具在測試之前自動加載,所以我把它拿出來了。 t改變一件事情。)

當然,因爲我似乎無法在這些地方找到問題,所以它可能就在其他地方。

回答

1

是否有可能阻止您的操作被調用?如果有一般:before_filter => 'login_required',那麼你可能根本沒有達到你的登錄功能。 (雖然承認註冊行爲將不得不被排除在測試之外)

在這種情況下,將某些日誌記錄(或通過調試器運行)看是否有用,以查看您是否可以訪問該部分你認爲失敗的方法。如果是我,我會將logger.debug("...")作爲登錄方法的第一行,然後在檢查request.post?之後再保留一個,然後在驗證檢查之後再插入一個。

+0

我不能相信我錯過了,但它實際上是過濾器。我最初命名爲函數log_in,然後出於審美原因將其重命名爲登錄 - 但我的過濾器例外從未得到更新。 謝謝! – dorr 2009-07-15 14:18:48