routing.rb 9.4 KB
Newer Older
J
Jeremy Kemper 已提交
1 2
require 'active_support/core_ext/hash/diff'

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

49
        request = recognized_request_for(path, request_method)
J
Joshua Peek 已提交
50

51 52
        expected_options = expected_options.clone
        extras.each_key { |key| expected_options.delete key } unless extras.nil?
J
Joshua Peek 已提交
53

54 55 56 57 58
        expected_options.stringify_keys!
        routing_diff = expected_options.diff(request.path_parameters)
        msg = build_message(message, "The recognized options <?> did not match <?>, difference: <?>",
            request.path_parameters, expected_options, expected_options.diff(request.path_parameters))
        assert_block(msg) { request.path_parameters == expected_options }
59 60
      end

P
Pratik Naik 已提交
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 68
      # ==== Examples
      #   # Asserts that the default action is generated for a route with no action
P
Pratik Naik 已提交
69
      #   assert_generates "/items", :controller => "items", :action => "index"
70 71
      #
      #   # Tests that the list action is properly routed
P
Pratik Naik 已提交
72
      #   assert_generates "/items/list", :controller => "items", :action => "list"
73 74
      #
      #   # Tests the generation of a route with a parameter
P
Pratik Naik 已提交
75
      #   assert_generates "/items/list/1", { :controller => "items", :action => "list", :id => "1" }
76 77 78
      #
      #   # Asserts that the generated route gives us our custom route
      #   assert_generates "changesets/12", { :controller => 'scm', :action => 'show_diff', :revision => "12" }
79
      def assert_generates(expected_path, options, defaults={}, extras = {}, message=nil)
80 81
        expected_path = "/#{expected_path}" unless expected_path[0] == ?/
        # Load routes.rb if it hasn't been loaded.
J
Joshua Peek 已提交
82

C
Carlhuda 已提交
83
        generated_path, extra_keys = @router.generate_extras(options, defaults)
84
        found_extras = options.reject {|k, v| ! extra_keys.include? k}
85

86 87
        msg = build_message(message, "found extras <?>, not <?>", found_extras, extras)
        assert_block(msg) { found_extras == extras }
J
Joshua Peek 已提交
88

89 90 91
        msg = build_message(message, "The generated path <?> did not match <?>", generated_path,
            expected_path)
        assert_block(msg) { expected_path == generated_path }
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
P
Pratik Naik 已提交
95 96
      # <tt>options</tt> and then that <tt>options</tt> generates <tt>path</tt>.  This essentially combines +assert_recognizes+
      # 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 102
      #
      # ==== Examples
      #  # Assert a basic route: a controller with the default action (index)
P
Pratik Naik 已提交
103
      #  assert_routing '/home', :controller => 'home', :action => 'index'
104 105
      #
      #  # Test a route generated with a specific controller, action, and parameter (id)
P
Pratik Naik 已提交
106
      #  assert_routing '/entries/show/23', :controller => 'entries', :action => 'show', :id => 23
107 108
      #
      #  # Assert a basic route (controller + default action), with an error message if it fails
P
Pratik Naik 已提交
109
      #  assert_routing '/store', { :controller => 'store', :action => 'index' }, {}, {}, 'Route for store index not generated properly'
110 111 112
      #
      #  # Tests a route, providing a defaults hash
      #  assert_routing 'controller/action/9', {:id => "9", :item => "square"}, {:controller => "controller", :action => "action"}, {}, {:item => "square"}
113 114
      #
      #  # Tests a route with a HTTP method
P
Pratik Naik 已提交
115
      #  assert_routing({ :method => 'put', :path => '/product/321' }, { :controller => "product", :action => "update", :id => "321" })
116 117
      def assert_routing(path, options, defaults={}, extras={}, message=nil)
        assert_recognizes(options, path, extras, message)
J
Joshua Peek 已提交
118 119

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

124
        assert_generates(path.is_a?(Hash) ? path[:path] : path, options, defaults, extras, message)
125 126
      end

J
Joshua Peek 已提交
127
      # A helper to make it easier to test different route configurations.
128
      # This method temporarily replaces @router
J
Joshua Peek 已提交
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
      # with a new RouteSet instance.
      #
      # The new instance is yielded to the passed block. Typically the block
      # will create some routes using <tt>map.draw { map.connect ... }</tt>:
      #
      #   with_routing do |set|
      #     set.draw do |map|
      #       map.connect ':controller/:action/:id'
      #         assert_equal(
      #           ['/content/10/show', {}],
      #           map.generate(:controller => 'content', :id => 10, :action => 'show')
      #       end
      #     end
      #   end
      #
      def with_routing
C
Carlhuda 已提交
145 146 147
        old_routes, @router = @router, ActionDispatch::Routing::RouteSet.new
        old_controller, @controller = @controller, @controller.clone if @controller
        _router = @router
148 149 150 151 152 153 154 155

        # 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
        if @controller
156 157 158 159
          @controller.singleton_class.send(:include, _router.url_helpers)
          @controller.view_context_class = Class.new(@controller.view_context_class) do
            include _router.url_helpers
          end
160
        end
C
Carlhuda 已提交
161
        yield @router
J
Joshua Peek 已提交
162
      ensure
C
Carlhuda 已提交
163
        @router = old_routes
164 165 166
        if @controller
          @controller = old_controller
        end
J
Joshua Peek 已提交
167 168
      end

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

178
      private
179
        # Recognizes the route for a given path.
180 181 182 183
        def recognized_request_for(path, request_method = nil)
          path = "/#{path}" unless path.first == '/'

          # Assume given controller
184
          request = ActionController::TestRequest.new
185
          request.env["REQUEST_METHOD"] = request_method.to_s.upcase if request_method
J
Joshua Peek 已提交
186 187
          request.path = path

C
Carlhuda 已提交
188
          params = @router.recognize_path(path, { :method => request.method })
J
Joshua Peek 已提交
189
          request.path_parameters = params.with_indifferent_access
190 191 192 193 194

          request
        end
    end
  end
195
end