开发者

How do I test that a before_filter will redirect for all Rails controller actions?

I have a fairly typical require_no_user as a before_filter in one of my controllers. I need to test that a logge开发者_如何学Pythond in user is redirected by this filter if they try to access any of the controller's actions.

Is there a sensible way to do this without enumerating all of the controller's actions in my test case?

I'm trying to avoid:

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


Not that I'm aware of... though you could make it a bit shorter by packing all the methods and actions into a hash:

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

Edit: so yeah, this is probably overkill, but here's another way:

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

Seems though that if you define multiple :methods in custom routes that it still only "finds" the first, e.g.

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

The above route will only be attempted with the GET verb.

Also if there are other requirements in the URL, such as presence of a record ID, my naive example ignores that requirement. I leave that up to you to hack out :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜