Rails 3: Get list of routes in namespace programmatically

浪子不回头ぞ 提交于 2019-11-27 14:59:22

问题


Question

How can I get a list of all the routes in my Admin namespace so that I can use it in one of my tests?

Rationale

I frequently make the mistake of inheriting from ApplicationController instead of AdminController when creating new controllers in my Admin namespace. So, I want to write a test that visits all the routes in my Admin namespace and verifies that each one requires a logged in user.


回答1:


test_routes = []

Rails.application.routes.routes.each do |route|
  route = route.path.spec.to_s
  test_routes << route if route.starts_with?('/admin')
end



回答2:


In case anybody else wants to test that all routes in a namespace require a logged in user, here's how I accomplished it:

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

I welcome improvements.



来源:https://stackoverflow.com/questions/19611104/rails-3-get-list-of-routes-in-namespace-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!