Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: Get list of routes in namespace programmatically

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.

like image 788
Richard Jones Avatar asked Oct 26 '13 19:10

Richard Jones


2 Answers

test_routes = []

Rails.application.routes.routes.each do |route|
  route = route.path.spec.to_s
  test_routes << route if route.starts_with?('/admin')
end
like image 132
d_ethier Avatar answered Nov 20 '22 22:11

d_ethier


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.

like image 14
Richard Jones Avatar answered Nov 20 '22 22:11

Richard Jones