2009-06-16 170 views
5

在我的一些控制器中,我有一個before_filter用來檢查用戶是否登錄?爲CRUD行動。功能測試Authlogic?

application.rb中

def logged_in? 
    unless current_user 
    redirect_to root_path 
    end 
end 

private 
def current_user_session 
    return @current_user_session if defined?(@current_user_session) 
    @current_user_session = UserSession.find 
end 

def current_user 
    return @current_user if defined?(@current_user) 
    @current_user = current_user_session && current_user_session.record 
end 

但現在我的功能測試失敗,因爲它重定向到根。所以我需要一種方法來模擬一個會話已經創建,但沒有我試過的工作。下面有什麼,我現在所擁有的,並測試幾乎忽略它:

test_helper.rb中

class ActionController::TestCase 
    setup :activate_authlogic 
end 

posts_controller_test.rb

class PostsControllerTest < ActionController::TestCase 
    setup do 
    UserSession.create(:username => "dmix", :password => "12345") 
    end 

    test "should get new" do 
    get :new 
    assert_response :success 
    end 

我缺少的東西?

回答

5

你應該通過ActiveRecord的對象UserSession.create

喜歡的東西:

u = users(:dmix) 
UserSession.create(u) 
+3

如果你有一個不依賴於它們的應用程序,我真的鼓勵你不要使用燈具進行測試。他們很難維持,真正令人沮喪。看看railscast,工廠沒有燈具。 – nitecoder 2009-06-16 22:13:49

+0

通過創建一個這樣的用戶,您不會測試您的控制器中是否調用了相應的檢查程序(例如必須登錄,必須是管理員等)。最好嘲笑預期的方法以確保它們被呼叫,例如對於摩卡:模擬(@controller).expects(:current_user).returns(@user) – 2011-07-28 16:12:59

3

我在我的控制器的rspec測試中做的所有事情是創建一個User with Machinist,然後將該用戶分配給current_user。

def login_user(options = {}) 
    user = User.make(options) 
    @controller.stub!(:current_user).and_return(user) 
end 

並且這將current_user附加到控制器,這意味着您的logged_in?方法可以在你的測試中工作。

你顯然可能需要適應這個在Test :: Unit中工作,如果你不使用它,而不使用Machinist,因爲我使用rspec,但我確定原理是一樣的。

4

http://rdoc.info/github/binarylogic/authlogic/master/Authlogic/TestCase

首先,你需要激活AuthLogic,讓您可以在您的測試中使用它。

setup :activate_authlogic 

然後,您需要一個有效的用戶記錄,如Anton Mironov指出的那樣。如果你希望所有的測試設置Authlogic

+0

鏈接到文檔是死的,試試這裏:http://rdoc.info/github/binarylogic/authlogic/master/Authlogic/ TestCase – 2011-07-03 20:32:51

1

把這個test_helper.rb

class ActionController::TestCase 
    def self.inherited(subclass) 
    subclass.instance_eval do 
     setup :activate_authlogic 
    end 
    end 
end 
0

Here是對AuthLogic測試文檔的鏈接。這是一個重要的,但有點埋沒(Simone發佈了同樣的鏈接,但他沒有工作了)。

該頁面提供了使用AuthLogic進行身份驗證測試應用程序所需的所有信息。

此外,正如railsninja建議的,使用工廠而不是固定裝置。看看factory_girlmachinist;挑你的毒藥,他們都很好。