[英]How do I test that a before_filter will redirect for all Rails controller actions?
我在一個控制器中有一個非常典型的require_no_user
作為before_filter
。 如果他們嘗試訪問控制器的任何操作 ,則需要測試該過濾器是否重定向了登錄用戶。
有沒有一種明智的方式可以做到這一點,而無需在測試用例中枚舉控制器的所有動作?
我試圖避免:
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
並不是我知道的...盡管您可以通過將所有方法和操作打包到一個哈希中來使它更短一些:
should "be redirected" do
{
:get => :new,
:post => :create,
}.each do |method, action|
send(method, action)
assert_redirected_to(root_path)
end
end
編輯:是的,這可能是矯kill過正,但這是另一種方式:
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
似乎,如果您在自定義路由中定義了多個:method,它仍然只會“發現”第一個方法,例如
map.resources :foo, :collection => {
:bar => [:get, :post]
}
僅使用GET動詞嘗試上述路線。
另外,如果URL中還有其他要求,例如是否存在記錄ID,則我的幼稚示例將忽略該要求。 我留給你自己來破解:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.