routing.rb 9.8 KB
Newer Older
1
require 'uri'
2
require 'active_support/core_ext/hash/indifferent_access'
3
require 'action_controller/metal/exceptions'
J
Jeremy Kemper 已提交
4

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

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

44
        expected_options.stringify_keys!
45 46

        message ||= sprintf("The recognized options <%s> did not match <%s>, difference: <%s>",
S
Steve Klabnik 已提交
47
            request.path_parameters, expected_options, diff(expected_options, request.path_parameters))
48
        assert_equal(expected_options, request.path_parameters, message)
49 50
      end

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

J
Joshua Peek 已提交
79
        generated_path, extra_keys = @routes.generate_extras(options, defaults)
80
        found_extras = options.reject {|k, v| ! extra_keys.include? k}
81

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

85
        msg = message || sprintf("The generated path <%s> did not match <%s>", generated_path,
86
            expected_path)
87
        assert_equal(expected_path, generated_path, msg)
88 89
      end

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

        controller, default_controller = options[:controller], defaults[:controller]
115 116 117
        if controller && controller.include?(?/) && default_controller && default_controller.include?(?/)
          options[:controller] = "/#{controller}"
        end
J
Joshua Peek 已提交
118

119 120
        generate_options = options.dup.delete_if{ |k,v| defaults.key?(k) }
        assert_generates(path.is_a?(Hash) ? path[:path] : path, generate_options, defaults, extras, message)
121 122
      end

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

143 144 145 146 147 148
          # 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 已提交
149
          @controller.singleton_class.send(:include, _routes.url_helpers)
150
          @controller.view_context_class = Class.new(@controller.view_context_class) do
J
Joshua Peek 已提交
151
            include _routes.url_helpers
152
          end
153
        end
J
Joshua Peek 已提交
154
        yield @routes
J
Joshua Peek 已提交
155
      ensure
J
Joshua Peek 已提交
156
        @routes = old_routes
157
        if defined?(@controller) && @controller
158 159
          @controller = old_controller
        end
J
Joshua Peek 已提交
160 161
      end

162
      # ROUTES TODO: These assertions should really work in an integration context
J
Joshua Peek 已提交
163
      def method_missing(selector, *args, &block)
164
        if defined?(@controller) && @controller && @routes && @routes.named_routes.helpers.include?(selector)
J
Joshua Peek 已提交
165 166 167 168 169 170
          @controller.send(selector, *args, &block)
        else
          super
        end
      end

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

          # Assume given controller
182
          request = ActionController::TestRequest.new
J
Joshua Peek 已提交
183

184
          if path =~ %r{://}
185
            fail_on(URI::InvalidURIError) do
186 187 188 189 190 191 192 193 194 195 196 197 198
              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

199 200 201
          params = fail_on(ActionController::RoutingError) do
            @routes.recognize_path(path, { :method => method, :extras => extras })
          end
J
Joshua Peek 已提交
202
          request.path_parameters = params.with_indifferent_access
203 204 205

          request
        end
206 207 208 209 210 211 212 213

        def fail_on(exception_class)
          begin
            yield
          rescue exception_class => e
            raise MiniTest::Assertion, e.message
          end
        end
214 215
    end
  end
216
end