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
      #   # assert 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 21 22
      # You can also pass in +extras+ with a hash containing URL parameters that would normally be in the query string. This can be used
      # to assert that values in the query string string will end up in the params hash correctly. To test query strings you must use the
      # extras argument, appending the query string on the path directly will not work. For example:
23 24
      #
      #   # assert 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
        request = recognized_request_for(path, extras)
J
Joshua Peek 已提交
42

43
        expected_options = expected_options.clone
J
Joshua Peek 已提交
44

45
        expected_options.stringify_keys!
46

47 48 49 50 51 52
        msg = message(msg, "") {
          sprintf("The recognized options <%s> did not match <%s>, difference:",
                  request.path_parameters, expected_options)
        }

        assert_equal(expected_options, request.path_parameters, msg)
53 54
      end

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

J
Joshua Peek 已提交
83
        generated_path, extra_keys = @routes.generate_extras(options, defaults)
84
        found_extras = options.reject { |k, _| ! extra_keys.include? k }
85

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

89
        msg = message || sprintf("The generated path <%s> did not match <%s>", generated_path,
90
            expected_path)
91
        assert_equal(expected_path, generated_path, msg)
92 93
      end

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

        controller, default_controller = options[:controller], defaults[:controller]
119 120 121
        if controller && controller.include?(?/) && default_controller && default_controller.include?(?/)
          options[:controller] = "/#{controller}"
        end
J
Joshua Peek 已提交
122

123
        generate_options = options.dup.delete_if{ |k, _| defaults.key?(k) }
124
        assert_generates(path.is_a?(Hash) ? path[:path] : path, generate_options, defaults, extras, message)
125 126
      end

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

147 148 149 150 151 152
          # Unfortunately, there is currently an abstraction leak between AC::Base
          # and AV::Base which requires having the URL helpers in both AC and AV.
          # To do this safely at runtime for tests, we need to bump up the helper serial
          # to that the old AV subclass isn't cached.
          #
          # TODO: Make this unnecessary
J
Joshua Peek 已提交
153
          @controller.singleton_class.send(: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)
168
        if defined?(@controller) && @controller && @routes && @routes.named_routes.helpers.include?(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 = {})
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.new
J
Joshua Peek 已提交
187

188
          if path =~ %r{://}
189
            fail_on(URI::InvalidURIError) 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 204 205
          params = fail_on(ActionController::RoutingError) do
            @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)
212 213
          yield
        rescue exception_class => e
214
          raise Minitest::Assertion, e.message
215
        end
216 217
    end
  end
218
end