Rails 3: Get list of routes in namespace programmatically

后端 未结 2 1074
深忆病人
深忆病人 2020-12-15 08:38

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 frequentl

相关标签:
2条回答
  • 2020-12-15 09:15
    test_routes = []
    
    Rails.application.routes.routes.each do |route|
      route = route.path.spec.to_s
      test_routes << route if route.starts_with?('/admin')
    end
    
    0 讨论(0)
  • 2020-12-15 09:15

    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.

    0 讨论(0)
提交回复
热议问题