2011-02-22 73 views
3

在我的一個控制器中,我有一個相當典型的require_no_user作爲before_filter。如果他們嘗試訪問控制器操作的任何,我需要測試一個登錄用戶是否被該過濾器重定向。如何測試before_filter將重定向所有Rails控制器操作?

有沒有一個明智的方法來做到這一點,而不用枚舉我的測試用例中的所有控制器的動作?

我試圖避免:

context 'An authenticated user' do 
    setup do 
    activate_authlogic 
    @user = Factory(:user) 
    UserSession.create(@user) 
    do 

    should 'not be allowed to GET :new' do 
    get :new 
    assert_redirected_to(root_path) 
    end 

    should 'not be allowed to POST :create' do 
    # same as above 
    end 

    # Repeat for every controller action 
end 

回答

2

這並不是說我知道的......雖然你可以使它有點短用所有的方法和行動包裝成一個哈希:

should "be redirected" do 
    { 
    :get => :new, 
    :post => :create, 
    }.each do |method, action| 
    send(method, action) 
    assert_redirected_to(root_path) 
    end 
end 

編輯:所以是的,這可能是矯枉過正,但這裏的另一種方式:

should "be redirected" do 
    ActionController::Routing::Routes.named_routes.routes.each do |name, route| 
    if route.requirements[:controller] == @controller.controller_name 
     send(route.conditions[:method], route.requirements[:action]) 
     assert_redirected_to(root_path) 
    end 
    end 
end 

看來的是,如果你去罰款倍數:自定義路線中的方法,它仍然只是「找到」第一個,例如

map.resources :foo, :collection => { 
    :bar => [:get, :post] 
} 

上述路線只會嘗試使用GET動詞。

此外,如果URL中還存在其他需求,例如存在記錄ID,那麼我的天真示例將忽略該要求。我留給你,以破解:)

+0

謝謝,它整理了一下 - 但它仍然需要我列舉所有的行動,這會導致問題,如果我在控制器中添加新的,忘記把它們在測試中。 – nfm 2011-02-23 06:05:55

+0

只要你定義了沒有':only'或':except'條件的過濾器,即你只是使用'before_filter:require_no_user',我就不用擔心它。 Rails核心測試負責證明'before_filter'實際上起作用。 – jemminger 2011-02-23 17:12:12

+0

沒錯;這是一個'before_filter'。我想我很擔心一個':only'或者':except'參數被意外添加到軌道上,沒有測試用例可以解決這個問題。我是否過於肛門?我是新手,並且仍然在學習如何編寫明智的測試用例。你怎麼看? – nfm 2011-02-23 23:20:32

相關問題