routing.rb 9.8 KB
Newer Older
1
require 'uri'
2
require 'active_support/core_ext/hash/indifferent_access'
A
Akira Matsuda 已提交
3
require 'active_support/core_ext/string/access'
4
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" }
R
Rafael Mendonça França 已提交
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 85 86
            uri = URI.parse(expected_path)
            expected_path = uri.path.to_s.empty? ? "/" : uri.path
          end
        else
          expected_path = "/#{expected_path}" unless expected_path.first == '/'
        end
87
        # Load routes.rb if it hasn't been loaded.
J
Joshua Peek 已提交
88

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

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

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

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

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

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

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

153
          @controller.singleton_class.include(_routes.url_helpers)
154
          @controller.view_context_class = Class.new(@controller.view_context_class) do
J
Joshua Peek 已提交
155
            include _routes.url_helpers
156
          end
157
        end
J
Joshua Peek 已提交
158
        yield @routes
J
Joshua Peek 已提交
159
      ensure
J
Joshua Peek 已提交
160
        @routes = old_routes
161
        if defined?(@controller) && @controller
162 163
          @controller = old_controller
        end
J
Joshua Peek 已提交
164 165
      end

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

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

          # Assume given controller
186
          request = ActionController::TestRequest.create
J
Joshua Peek 已提交
187

188
          if path =~ %r{://}
189
            fail_on(URI::InvalidURIError, msg) do
190 191 192 193 194 195 196 197 198 199 200 201 202
              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

203
          params = fail_on(ActionController::RoutingError, msg) do
204 205
            @routes.recognize_path(path, { :method => method, :extras => extras })
          end
J
Joshua Peek 已提交
206
          request.path_parameters = params.with_indifferent_access
207 208 209

          request
        end
210

211
        def fail_on(exception_class, message)
212 213
          yield
        rescue exception_class => e
214
          raise Minitest::Assertion, message || e.message
215
        end
216 217
    end
  end
218
end