17

问题

如何获取我的Admin命名空间中所有路由的列表,以便我可以在我的一个测试中使用它?

基本原理

ApplicationController在我的命名空间中AdminController创建新控制器时,我经常犯下继承的错误Admin。因此,我想编写一个测试来访问我的Admin命名空间中的所有路由并验证每个路由都需要一个登录用户。

4

2 回答 2

22
test_routes = []

Rails.application.routes.routes.each do |route|
  route = route.path.spec.to_s
  test_routes << route if route.starts_with?('/admin')
end
于 2013-10-26T20:12:05.513 回答
12

如果其他人想测试命名空间中的所有路由是否需要登录用户,我是这样做的:

ROUTES = Rails.application.routes.routes.map do |route|
  # Turn route path spec into string; use "1" for all params
  path = route.path.spec.to_s.gsub(/\(\.:format\)/, "").gsub(/:[a-zA-Z_]+/, "1")
  verb = %W{ GET POST PUT PATCH DELETE }.grep(route.verb).first.downcase.to_sym
  { path: path, verb: verb }
end

test "admin routes should redirect to admin login page when no admin user is logged in" do
  admin_routes = ROUTES.select { |route| route[:path].starts_with? "/admin" }
  unprotected_routes = []

  admin_routes.each do |route|
    begin
      reset!
      request_via_redirect(route[:verb], route[:path])
      unprotected_routes << "#{route[:verb]} #{route[:path]}" unless path == admin_login_path
    rescue ActiveRecord::RecordNotFound
      unprotected_routes << "#{route[:verb]} #{route[:path]}" unless path == admin_login_path
    rescue AbstractController::ActionNotFound
    end
  end

  assert unprotected_routes.empty?,
    "The following routes are not secure: \n\t#{unprotected_routes.uniq.join("\n\t")}"
  end
end

我欢迎改进。

于 2013-10-28T05:51:40.440 回答