routing.rb 10.1 KB
Newer Older
1
require 'uri'
J
Jeremy Kemper 已提交
2
require 'active_support/core_ext/hash/diff'
3
require 'active_support/core_ext/hash/indifferent_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
P
Pratik Naik 已提交
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
P
Pratik Naik 已提交
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)
P
Pratik Naik 已提交
30
      #   assert_recognizes({:controller => 'items', :action => 'index'}, 'items')
31 32
      #
      #   # Test a specific action
P
Pratik Naik 已提交
33
      #   assert_recognizes({:controller => 'items', :action => 'list'}, 'items/list')
34 35
      #
      #   # Test an action with a parameter
P
Pratik Naik 已提交
36
      #   assert_recognizes({:controller => 'items', :action => 'destroy', :id => '1'}, 'items/destroy/1')
37 38
      #
      #   # Test a custom route
P
Pratik Naik 已提交
39
      #   assert_recognizes({:controller => 'items', :action => 'show', :id => '1'}, 'view/item1')
40
      def assert_recognizes(expected_options, path, extras={}, message=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

        # FIXME: minitest does object diffs, do we need to have our own?
        message ||= sprintf("The recognized options <%s> did not match <%s>, difference: <%s>",
49
            request.path_parameters, expected_options, expected_options.diff(request.path_parameters))
50
        assert_equal(expected_options, request.path_parameters, message)
51 52
      end

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

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

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

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

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

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

121 122
        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)
123 124
      end

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

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

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

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

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

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

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

          request
        end
208 209 210 211 212 213 214 215

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