routing.rb 9.9 KB
Newer Older
1 2 3 4
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 已提交
5

6
module ActionDispatch
7
  module Assertions
8
    # Suite of assertions to test routes generated by \Rails and the handling of requests made to them.
9
    module RoutingAssertions
J
Joshua Peek 已提交
10
      # Asserts that the routing of the given +path+ was handled correctly and that the parsed options (given in the +expected_options+ hash)
11
      # match +path+. Basically, it asserts that \Rails recognizes the route given by +expected_options+.
12
      #
13 14
      # 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
15
      # and a :method containing the required HTTP verb.
16
      #
17
      #   # Asserts that POSTing to /items will call the create action on ItemsController
A
AvnerCohen 已提交
18
      #   assert_recognizes({controller: 'items', action: 'create'}, {path: 'items', method: :post})
19
      #
20
      # You can also pass in +extras+ with a hash containing URL parameters that would normally be in the query string. This can be used
J
Jake Worth 已提交
21
      # to assert that values in the query string will end up in the params hash correctly. To test query strings you must use the
22
      # extras argument, appending the query string on the path directly will not work. For example:
23
      #
24
      #   # Asserts that a path of '/items/list/1?view=print' returns the correct options
A
AvnerCohen 已提交
25
      #   assert_recognizes({controller: 'items', action: 'list', id: '1', view: 'print'}, 'items/list/1', { view: "print" })
26
      #
J
Joshua Peek 已提交
27
      # The +message+ parameter allows you to pass in an error message that is displayed upon failure.
28 29
      #
      #   # Check the default route (i.e., the index action)
A
AvnerCohen 已提交
30
      #   assert_recognizes({controller: 'items', action: 'index'}, 'items')
31 32
      #
      #   # Test a specific action
A
AvnerCohen 已提交
33
      #   assert_recognizes({controller: 'items', action: 'list'}, 'items/list')
34 35
      #
      #   # Test an action with a parameter
A
AvnerCohen 已提交
36
      #   assert_recognizes({controller: 'items', action: 'destroy', id: '1'}, 'items/destroy/1')
37 38
      #
      #   # Test a custom route
A
AvnerCohen 已提交
39
      #   assert_recognizes({controller: 'items', action: 'show', id: '1'}, 'view/item1')
40
      def assert_recognizes(expected_options, path, extras = {}, msg = nil)
41 42 43 44 45 46
        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 已提交
47

48
          expected_options = expected_options.clone
J
Joshua Peek 已提交
49

50
          expected_options.stringify_keys!
51

52 53 54 55
          msg = message(msg, "") {
            sprintf("The recognized options <%s> did not match <%s>, difference:",
                    request.path_parameters, expected_options)
          }
56

57 58
          assert_equal(expected_options, request.path_parameters, msg)
        end
59 60
      end

61
      # Asserts that the provided options can be used to generate the provided path. This is the inverse of +assert_recognizes+.
62 63
      # 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.
64
      #
65
      # The +defaults+ parameter is unused.
J
Joshua Peek 已提交
66
      #
67
      #   # Asserts that the default action is generated for a route with no action
A
AvnerCohen 已提交
68
      #   assert_generates "/items", controller: "items", action: "index"
69 70
      #
      #   # Tests that the list action is properly routed
A
AvnerCohen 已提交
71
      #   assert_generates "/items/list", controller: "items", action: "list"
72 73
      #
      #   # Tests the generation of a route with a parameter
A
AvnerCohen 已提交
74
      #   assert_generates "/items/list/1", { controller: "items", action: "list", id: "1" }
75 76
      #
      #   # Asserts that the generated route gives us our custom route
A
AvnerCohen 已提交
77
      #   assert_generates "changesets/12", { controller: 'scm', action: 'show_diff', revision: "12" }
78
      def assert_generates(expected_path, options, defaults = {}, extras = {}, message = nil)
79
        if expected_path =~ %r{://}
80
          fail_on(URI::InvalidURIError, message) do
81 82 83 84
            uri = URI.parse(expected_path)
            expected_path = uri.path.to_s.empty? ? "/" : uri.path
          end
        else
85
          expected_path = "/#{expected_path}" unless expected_path.first == "/"
86
        end
87
        # Load routes.rb if it hasn't been loaded.
J
Joshua Peek 已提交
88

89
        options = options.clone
90 91
        generated_path, query_string_keys = @routes.generate_extras(options, defaults)
        found_extras = options.reject { |k, _| ! query_string_keys.include? k }
92

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

96
        msg = message || sprintf("The generated path <%s> did not match <%s>", generated_path,
97
            expected_path)
98
        assert_equal(expected_path, generated_path, msg)
99 100
      end

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

        controller, default_controller = options[:controller], defaults[:controller]
126 127 128
        if controller && controller.include?(?/) && default_controller && default_controller.include?(?/)
          options[:controller] = "/#{controller}"
        end
J
Joshua Peek 已提交
129

130
        generate_options = options.dup.delete_if { |k, _| defaults.key?(k) }
131
        assert_generates(path.is_a?(Hash) ? path[:path] : path, generate_options, defaults, extras, message)
132 133
      end

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

154
          @controller.singleton_class.include(_routes.url_helpers)
155 156 157 158 159

          if @controller.respond_to? :view_context_class
            @controller.view_context_class = Class.new(@controller.view_context_class) do
              include _routes.url_helpers
            end
160
          end
161
        end
J
Joshua Peek 已提交
162
        yield @routes
J
Joshua Peek 已提交
163
      ensure
J
Joshua Peek 已提交
164
        @routes = old_routes
165
        if defined?(@controller) && @controller
166 167
          @controller = old_controller
        end
J
Joshua Peek 已提交
168 169
      end

170
      # ROUTES TODO: These assertions should really work in an integration context
J
Joshua Peek 已提交
171
      def method_missing(selector, *args, &block)
A
Akira Matsuda 已提交
172
        if defined?(@controller) && @controller && defined?(@routes) && @routes && @routes.named_routes.route_defined?(selector)
J
Joshua Peek 已提交
173 174 175 176 177 178
          @controller.send(selector, *args, &block)
        else
          super
        end
      end

179
      private
180
        # Recognizes the route for a given path.
181
        def recognized_request_for(path, extras = {}, msg)
182 183 184 185 186 187
          if path.is_a?(Hash)
            method = path[:method]
            path   = path[:path]
          else
            method = :get
          end
188 189

          # Assume given controller
190
          request = ActionController::TestRequest.create @controller.class
J
Joshua Peek 已提交
191

192
          if path =~ %r{://}
193
            fail_on(URI::InvalidURIError, msg) do
194 195 196 197 198 199 200 201 202 203 204 205 206
              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
            path = "/#{path}" unless path.first == "/"
            request.path = path
          end

          request.request_method = method if method

207
          params = fail_on(ActionController::RoutingError, msg) do
208
            @routes.recognize_path(path, method: method, extras: extras)
209
          end
J
Joshua Peek 已提交
210
          request.path_parameters = params.with_indifferent_access
211 212 213

          request
        end
214

215
        def fail_on(exception_class, message)
216 217
          yield
        rescue exception_class => e
218
          raise Minitest::Assertion, message || e.message
219
        end
220 221
    end
  end
222
end