routing.rb 10.2 KB
Newer Older
1 2
# frozen_string_literal: true

3 4 5 6
require "uri"
require "active_support/core_ext/hash/indifferent_access"
require "active_support/core_ext/string/access"
require "action_controller/metal/exceptions"
J
Jeremy Kemper 已提交
7

8
module ActionDispatch
9
  module Assertions
10
    # Suite of assertions to test routes generated by \Rails and the handling of requests made to them.
11
    module RoutingAssertions
12
      def setup # :nodoc:
A
Aaron Patterson 已提交
13
        @routes ||= nil
14 15 16
        super
      end

J
Joshua Peek 已提交
17
      # Asserts that the routing of the given +path+ was handled correctly and that the parsed options (given in the +expected_options+ hash)
18
      # match +path+. Basically, it asserts that \Rails recognizes the route given by +expected_options+.
19
      #
20 21
      # Pass a hash in the second argument (+path+) to specify the request method. This is useful for routes
      # requiring a specific HTTP method. The hash should contain a :path with the incoming request path
22
      # and a :method containing the required HTTP verb.
23
      #
24
      #   # Asserts that POSTing to /items will call the create action on ItemsController
A
AvnerCohen 已提交
25
      #   assert_recognizes({controller: 'items', action: 'create'}, {path: 'items', method: :post})
26
      #
27
      # You can also pass in +extras+ with a hash containing URL parameters that would normally be in the query string. This can be used
28 29
      # to assert that values in the query string will end up in the params hash correctly. To test query strings you must use the extras
      # argument because appending the query string on the path directly will not work. For example:
30
      #
31
      #   # Asserts that a path of '/items/list/1?view=print' returns the correct options
A
AvnerCohen 已提交
32
      #   assert_recognizes({controller: 'items', action: 'list', id: '1', view: 'print'}, 'items/list/1', { view: "print" })
33
      #
J
Joshua Peek 已提交
34
      # The +message+ parameter allows you to pass in an error message that is displayed upon failure.
35 36
      #
      #   # Check the default route (i.e., the index action)
A
AvnerCohen 已提交
37
      #   assert_recognizes({controller: 'items', action: 'index'}, 'items')
38 39
      #
      #   # Test a specific action
A
AvnerCohen 已提交
40
      #   assert_recognizes({controller: 'items', action: 'list'}, 'items/list')
41 42
      #
      #   # Test an action with a parameter
A
AvnerCohen 已提交
43
      #   assert_recognizes({controller: 'items', action: 'destroy', id: '1'}, 'items/destroy/1')
44 45
      #
      #   # Test a custom route
A
AvnerCohen 已提交
46
      #   assert_recognizes({controller: 'items', action: 'show', id: '1'}, 'view/item1')
47
      def assert_recognizes(expected_options, path, extras = {}, msg = nil)
48 49 50 51 52 53
        if path.is_a?(Hash) && path[:method].to_s == "all"
          [:get, :post, :put, :delete].each do |method|
            assert_recognizes(expected_options, path.merge(method: method), extras, msg)
          end
        else
          request = recognized_request_for(path, extras, msg)
J
Joshua Peek 已提交
54

55
          expected_options = expected_options.clone
J
Joshua Peek 已提交
56

57
          expected_options.stringify_keys!
58

59 60 61 62
          msg = message(msg, "") {
            sprintf("The recognized options <%s> did not match <%s>, difference:",
                    request.path_parameters, expected_options)
          }
63

64 65
          assert_equal(expected_options, request.path_parameters, msg)
        end
66 67
      end

68
      # Asserts that the provided options can be used to generate the provided path. This is the inverse of +assert_recognizes+.
69 70
      # The +extras+ parameter is used to tell the request the names and values of additional request parameters that would be in
      # a query string. The +message+ parameter allows you to specify a custom error message for assertion failures.
71
      #
72
      # The +defaults+ parameter is unused.
J
Joshua Peek 已提交
73
      #
74
      #   # Asserts that the default action is generated for a route with no action
A
AvnerCohen 已提交
75
      #   assert_generates "/items", controller: "items", action: "index"
76 77
      #
      #   # Tests that the list action is properly routed
A
AvnerCohen 已提交
78
      #   assert_generates "/items/list", controller: "items", action: "list"
79 80
      #
      #   # Tests the generation of a route with a parameter
A
AvnerCohen 已提交
81
      #   assert_generates "/items/list/1", { controller: "items", action: "list", id: "1" }
82 83
      #
      #   # Asserts that the generated route gives us our custom route
A
AvnerCohen 已提交
84
      #   assert_generates "changesets/12", { controller: 'scm', action: 'show_diff', revision: "12" }
85
      def assert_generates(expected_path, options, defaults = {}, extras = {}, message = nil)
86
        if %r{://}.match?(expected_path)
87
          fail_on(URI::InvalidURIError, message) do
88 89 90 91
            uri = URI.parse(expected_path)
            expected_path = uri.path.to_s.empty? ? "/" : uri.path
          end
        else
92
          expected_path = "/#{expected_path}" unless expected_path.start_with?("/")
93
        end
J
Joshua Peek 已提交
94

95
        options = options.clone
96 97
        generated_path, query_string_keys = @routes.generate_extras(options, defaults)
        found_extras = options.reject { |k, _| ! query_string_keys.include? k }
98

99
        msg = message || sprintf("found extras <%s>, not <%s>", found_extras, extras)
100
        assert_equal(extras, found_extras, msg)
J
Joshua Peek 已提交
101

102
        msg = message || sprintf("The generated path <%s> did not match <%s>", generated_path,
103
            expected_path)
104
        assert_equal(expected_path, generated_path, msg)
105 106
      end

J
Joshua Peek 已提交
107
      # Asserts that path and options match both ways; in other words, it verifies that <tt>path</tt> generates
108
      # <tt>options</tt> and then that <tt>options</tt> generates <tt>path</tt>. This essentially combines +assert_recognizes+
P
Pratik Naik 已提交
109
      # and +assert_generates+ into one step.
110
      #
111
      # The +extras+ hash allows you to specify options that would normally be provided as a query string to the action. The
J
Joshua Peek 已提交
112
      # +message+ parameter allows you to specify a custom error message to display upon failure.
113
      #
114
      #  # Asserts a basic route: a controller with the default action (index)
A
AvnerCohen 已提交
115
      #  assert_routing '/home', controller: 'home', action: 'index'
116 117
      #
      #  # Test a route generated with a specific controller, action, and parameter (id)
A
AvnerCohen 已提交
118
      #  assert_routing '/entries/show/23', controller: 'entries', action: 'show', id: 23
119
      #
120
      #  # Asserts a basic route (controller + default action), with an error message if it fails
A
AvnerCohen 已提交
121
      #  assert_routing '/store', { controller: 'store', action: 'index' }, {}, {}, 'Route for store index not generated properly'
122 123
      #
      #  # Tests a route, providing a defaults hash
A
AvnerCohen 已提交
124
      #  assert_routing 'controller/action/9', {id: "9", item: "square"}, {controller: "controller", action: "action"}, {}, {item: "square"}
125
      #
126
      #  # Tests a route with an HTTP method
A
AvnerCohen 已提交
127
      #  assert_routing({ method: 'put', path: '/product/321' }, { controller: "product", action: "update", id: "321" })
128
      def assert_routing(path, options, defaults = {}, extras = {}, message = nil)
129
        assert_recognizes(options, path, extras, message)
J
Joshua Peek 已提交
130 131

        controller, default_controller = options[:controller], defaults[:controller]
132 133 134
        if controller && controller.include?(?/) && default_controller && default_controller.include?(?/)
          options[:controller] = "/#{controller}"
        end
J
Joshua Peek 已提交
135

136
        generate_options = options.dup.delete_if { |k, _| defaults.key?(k) }
137
        assert_generates(path.is_a?(Hash) ? path[:path] : path, generate_options, defaults, extras, message)
138 139
      end

J
Joshua Peek 已提交
140
      # A helper to make it easier to test different route configurations.
141
      # This method temporarily replaces @routes with a new RouteSet instance.
J
Joshua Peek 已提交
142 143
      #
      # The new instance is yielded to the passed block. Typically the block
144
      # will create some routes using <tt>set.draw { match ... }</tt>:
J
Joshua Peek 已提交
145 146
      #
      #   with_routing do |set|
147 148
      #     set.draw do
      #       resources :users
J
Joshua Peek 已提交
149
      #     end
150
      #     assert_equal "/users", users_path
J
Joshua Peek 已提交
151 152 153
      #   end
      #
      def with_routing
154 155 156 157 158 159 160 161
        old_routes, @routes = @routes, ActionDispatch::Routing::RouteSet.new
        if defined?(@controller) && @controller
          old_controller, @controller = @controller, @controller.clone
          _routes = @routes

          @controller.singleton_class.include(_routes.url_helpers)

          if @controller.respond_to? :view_context_class
162
            view_context_class = Class.new(@controller.view_context_class) do
163
              include _routes.url_helpers
164
            end
165 166 167 168 169 170 171

            custom_view_context = Module.new {
              define_method(:view_context_class) do
                view_context_class
              end
            }
            @controller.extend(custom_view_context)
172
          end
173
        end
J
Joshua Peek 已提交
174
        yield @routes
J
Joshua Peek 已提交
175
      ensure
J
Joshua Peek 已提交
176
        @routes = old_routes
177
        if defined?(@controller) && @controller
178 179
          @controller = old_controller
        end
J
Joshua Peek 已提交
180 181
      end

182
      # ROUTES TODO: These assertions should really work in an integration context
J
Joshua Peek 已提交
183
      def method_missing(selector, *args, &block)
A
Akira Matsuda 已提交
184
        if defined?(@controller) && @controller && defined?(@routes) && @routes && @routes.named_routes.route_defined?(selector)
J
Joshua Peek 已提交
185 186 187 188 189 190
          @controller.send(selector, *args, &block)
        else
          super
        end
      end

191
      private
192
        # Recognizes the route for a given path.
193
        def recognized_request_for(path, extras = {}, msg)
194 195 196 197 198 199
          if path.is_a?(Hash)
            method = path[:method]
            path   = path[:path]
          else
            method = :get
          end
200

201 202
          controller = @controller if defined?(@controller)
          request = ActionController::TestRequest.create controller&.class
J
Joshua Peek 已提交
203

204
          if %r{://}.match?(path)
205
            fail_on(URI::InvalidURIError, msg) do
206 207 208 209 210 211 212
              uri = URI.parse(path)
              request.env["rack.url_scheme"] = uri.scheme || "http"
              request.host = uri.host if uri.host
              request.port = uri.port if uri.port
              request.path = uri.path.to_s.empty? ? "/" : uri.path
            end
          else
213
            path = "/#{path}" unless path.start_with?("/")
214 215 216 217 218
            request.path = path
          end

          request.request_method = method if method

219
          params = fail_on(ActionController::RoutingError, msg) do
220
            @routes.recognize_path(path, method: method, extras: extras)
221
          end
J
Joshua Peek 已提交
222
          request.path_parameters = params.with_indifferent_access
223 224 225

          request
        end
226

227
        def fail_on(exception_class, message)
228 229
          yield
        rescue exception_class => e
230
          raise Minitest::Assertion, message || e.message
231
        end
232 233
    end
  end
234
end