test_case.rb 21.2 KB
Newer Older
1
require 'rack/session/abstract/id'
2
require 'active_support/core_ext/object/to_query'
3
require 'active_support/core_ext/module/anonymous'
A
Akira Matsuda 已提交
4
require 'active_support/core_ext/hash/keys'
5
require 'action_controller/template_assertions'
6 7
require 'rails-dom-testing'

8
module ActionController
9
  class TestRequest < ActionDispatch::TestRequest #:nodoc:
10 11 12
    DEFAULT_ENV = ActionDispatch::TestRequest::DEFAULT_ENV.dup
    DEFAULT_ENV.delete 'PATH_INFO'

13 14 15 16
    def initialize(env = {})
      super

      self.session = TestSession.new
17
      self.session_options = TestSession::DEFAULT_OPTIONS
18 19
    end

J
Joshua Peek 已提交
20
    def assign_parameters(routes, controller_path, action, parameters = {})
21 22
      parameters = parameters.symbolize_keys
      extra_keys = routes.extra_keys(parameters.merge(:controller => controller_path, :action => action))
23
      non_path_parameters = get? ? query_parameters : request_parameters
24

25
      parameters.each do |key, value|
26 27 28 29 30
        if value.is_a?(Array) && (value.frozen? || value.any?(&:frozen?))
          value = value.map{ |v| v.duplicable? ? v.dup : v }
        elsif value.is_a?(Hash) && (value.frozen? || value.any?{ |k,v| v.frozen? })
          value = Hash[value.map{ |k,v| [k, v.duplicable? ? v.dup : v] }]
        elsif value.frozen? && value.duplicable?
31
          value = value.dup
32 33
        end

34
        if extra_keys.include?(key) || key == :action || key == :controller
35 36
          non_path_parameters[key] = value
        else
37
          if value.is_a?(Array)
38
            value = value.map(&:to_param)
39 40 41 42
          else
            value = value.to_param
          end

43
          path_parameters[key] = value
44 45 46
        end
      end

47 48 49
      path_parameters[:controller] = controller_path
      path_parameters[:action] = action

50 51
      # Clear the combined params hash in case it was already referenced.
      @env.delete("action_dispatch.request.parameters")
52

53 54 55
      # Clear the filter cache variables so they're not stale
      @filtered_parameters = @filtered_env = @filtered_path = nil

56
      data = request_parameters.to_query
57 58 59 60 61 62 63 64
      @env['CONTENT_LENGTH'] = data.length.to_s
      @env['rack.input'] = StringIO.new(data)
    end

    def recycle!
      @formats = nil
      @env.delete_if { |k, v| k =~ /^(action_dispatch|rack)\.request/ }
      @env.delete_if { |k, v| k =~ /^action_dispatch\.rescue/ }
65
      @method = @request_method = nil
66
      @fullpath = @ip = @remote_ip = @protocol = nil
67
      @env['action_dispatch.request.query_parameters'] = {}
68 69 70 71 72 73 74 75
      @set_cookies ||= {}
      @set_cookies.update(Hash[cookie_jar.instance_variable_get("@set_cookies").map{ |k,o| [k,o[:value]] }])
      deleted_cookies = cookie_jar.instance_variable_get("@delete_cookies")
      @set_cookies.reject!{ |k,v| deleted_cookies.include?(k) }
      cookie_jar.update(rack_cookies)
      cookie_jar.update(cookies)
      cookie_jar.update(@set_cookies)
      cookie_jar.recycle!
76
    end
77 78 79 80 81 82

    private

    def default_env
      DEFAULT_ENV
    end
83 84 85 86
  end

  class TestResponse < ActionDispatch::TestResponse
    def recycle!
87
      initialize
88 89 90
    end
  end

91 92 93 94 95 96 97 98 99
  class LiveTestResponse < Live::Response
    def recycle!
      @body = nil
      initialize
    end

    def body
      @body ||= super
    end
100 101 102 103 104 105 106 107 108 109 110 111

    # Was the response successful?
    alias_method :success?, :successful?

    # Was the URL not found?
    alias_method :missing?, :not_found?

    # Were we redirected?
    alias_method :redirect?, :redirection?

    # Was there a server-side error?
    alias_method :error?, :server_error?
112 113
  end

114 115
  # Methods #destroy and #load! are overridden to avoid calling methods on the
  # @store object, which does not exist for the TestSession class.
116 117
  class TestSession < Rack::Session::Abstract::SessionHash #:nodoc:
    DEFAULT_OPTIONS = Rack::Session::Abstract::ID::DEFAULT_OPTIONS
118 119

    def initialize(session = {})
120
      super(nil, nil)
121 122
      @id = SecureRandom.hex(16)
      @data = stringify_keys(session)
123 124
      @loaded = true
    end
125

126 127 128
    def exists?
      true
    end
129

130 131 132 133 134 135 136 137
    def keys
      @data.keys
    end

    def values
      @data.values
    end

138 139 140 141 142 143 144 145 146
    def destroy
      clear
    end

    private

      def load!
        @id
      end
147 148
  end

P
Pratik Naik 已提交
149 150
  # Superclass for ActionController functional tests. Functional tests allow you to
  # test a single controller action per test method. This should not be confused with
151
  # integration tests (see ActionDispatch::IntegrationTest), which are more like
152
  # "stories" that can involve multiple controllers and multiple actions (i.e. multiple
P
Pratik Naik 已提交
153
  # different HTTP requests).
P
Pratik Naik 已提交
154
  #
P
Pratik Naik 已提交
155 156 157
  # == Basic example
  #
  # Functional tests are written as follows:
158
  # 1. First, one uses the +get+, +post+, +patch+, +put+, +delete+ or +head+ method to simulate
P
Pratik Naik 已提交
159 160 161 162 163 164 165 166 167
  #    an HTTP request.
  # 2. Then, one asserts whether the current state is as expected. "State" can be anything:
  #    the controller's HTTP response, the database contents, etc.
  #
  # For example:
  #
  #   class BooksControllerTest < ActionController::TestCase
  #     def test_create
  #       # Simulate a POST response with the given HTTP parameters.
A
AvnerCohen 已提交
168
  #       post(:create, book: { title: "Love Hina" })
P
Pratik Naik 已提交
169 170 171 172 173 174
  #
  #       # Assert that the controller tried to redirect us to
  #       # the created book's URI.
  #       assert_response :found
  #
  #       # Assert that the controller really put the book in the database.
175
  #       assert_not_nil Book.find_by(title: "Love Hina")
P
Pratik Naik 已提交
176 177 178
  #     end
  #   end
  #
179 180 181
  # You can also send a real document in the simulated HTTP request.
  #
  #   def test_create
A
AvnerCohen 已提交
182
  #     json = {book: { title: "Love Hina" }}.to_json
183
  #     post :create, json
R
Rafael Mendonça França 已提交
184
  #   end
185
  #
P
Pratik Naik 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
  # == Special instance variables
  #
  # ActionController::TestCase will also automatically provide the following instance
  # variables for use in the tests:
  #
  # <b>@controller</b>::
  #      The controller instance that will be tested.
  # <b>@request</b>::
  #      An ActionController::TestRequest, representing the current HTTP
  #      request. You can modify this object before sending the HTTP request. For example,
  #      you might want to set some session properties before sending a GET request.
  # <b>@response</b>::
  #      An ActionController::TestResponse object, representing the response
  #      of the last HTTP response. In the above example, <tt>@response</tt> becomes valid
  #      after calling +post+. If the various assert methods are not sufficient, then you
  #      may use this object to inspect the HTTP response in detail.
  #
J
Joost Baaij 已提交
203
  # (Earlier versions of \Rails required each functional test to subclass
P
Pratik Naik 已提交
204
  # Test::Unit::TestCase and define @controller, @request, @response in +setup+.)
P
Pratik Naik 已提交
205
  #
P
Pratik Naik 已提交
206
  # == Controller is automatically inferred
P
Pratik Naik 已提交
207
  #
P
Pratik Naik 已提交
208 209
  # ActionController::TestCase will automatically infer the controller under test
  # from the test class name. If the controller cannot be inferred from the test
P
Pratik Naik 已提交
210
  # class name, you can explicitly set it with +tests+.
P
Pratik Naik 已提交
211 212 213 214
  #
  #   class SpecialEdgeCaseWidgetsControllerTest < ActionController::TestCase
  #     tests WidgetController
  #   end
215
  #
J
Joost Baaij 已提交
216
  # == \Testing controller internals
217 218 219 220 221 222 223
  #
  # In addition to these specific assertions, you also have easy access to various collections that the regular test/unit assertions
  # can be used against. These collections are:
  #
  # * assigns: Instance variables assigned in the action that are available for the view.
  # * session: Objects being saved in the session.
  # * flash: The flash objects currently in the session.
J
Joost Baaij 已提交
224
  # * cookies: \Cookies being sent to the user on this request.
225 226 227 228 229 230 231
  #
  # These collections can be used just like any other hash:
  #
  #   assert_not_nil assigns(:person) # makes sure that a @person instance variable was set
  #   assert_equal "Dave", cookies[:name] # makes sure that a cookie called :name was set as "Dave"
  #   assert flash.empty? # makes sure that there's nothing in the flash
  #
232
  # For historic reasons, the assigns hash uses string-based keys. So <tt>assigns[:person]</tt> won't work, but <tt>assigns["person"]</tt> will. To
233
  # appease our yearning for symbols, though, an alternative accessor has been devised using a method call instead of index referencing.
234
  # So <tt>assigns(:person)</tt> will work just like <tt>assigns["person"]</tt>, but again, <tt>assigns[:person]</tt> will not work.
235
  #
236
  # On top of the collections, you have the complete url that a given action redirected to available in <tt>redirect_to_url</tt>.
237 238 239 240
  #
  # For redirects within the same controller, you can even call follow_redirect and the redirect will be followed, triggering another
  # action call which can then be asserted against.
  #
241
  # == Manipulating session and cookie variables
242
  #
243 244
  # Sometimes you need to set up the session and cookie variables for a test.
  # To do this just assign a value to the session or cookie collection:
245
  #
246 247
  #   session[:key] = "value"
  #   cookies[:key] = "value"
248
  #
249
  # To clear the cookies for a test just clear the cookie collection:
250
  #
251
  #   cookies.clear
252
  #
J
Joost Baaij 已提交
253
  # == \Testing named routes
254 255 256
  #
  # If you're using named routes, they can be easily tested using the original named routes' methods straight in the test case.
  #
A
AvnerCohen 已提交
257
  #  assert_redirected_to page_url(title: 'foo')
258
  class TestCase < ActiveSupport::TestCase
259 260 261
    module Behavior
      extend ActiveSupport::Concern
      include ActionDispatch::TestProcess
262
      include ActiveSupport::Testing::ConstantLookup
263
      include Rails::Dom::Testing::Assertions
264

265
      attr_reader :response, :request
266

267
      module ClassMethods
268

269
        # Sets the controller class name. Useful if the name can't be inferred from test class.
270
        # Normalizes +controller_class+ before using.
271 272 273 274
        #
        #   tests WidgetController
        #   tests :widget
        #   tests 'widget'
275
        def tests(controller_class)
276 277
          case controller_class
          when String, Symbol
278
            self.controller_class = "#{controller_class.to_s.camelize}Controller".constantize
279 280 281 282 283
          when Class
            self.controller_class = controller_class
          else
            raise ArgumentError, "controller class must be a String, Symbol, or Class"
          end
284
        end
285

286
        def controller_class=(new_class)
287
          self._controller_class = new_class
288
        end
289

290
        def controller_class
291
          if current_controller_class = self._controller_class
292 293 294 295 296
            current_controller_class
          else
            self.controller_class = determine_default_controller_class(name)
          end
        end
297

298
        def determine_default_controller_class(name)
299 300 301
          determine_constant_from_test_name(name) do |constant|
            Class === constant && constant < ActionController::Metal
          end
302
        end
303
      end
304

305 306
      # Simulate a GET request with the given parameters.
      #
307
      # - +action+: The controller action to call.
308 309
      # - +params+: The hash with HTTP parameters that you want to pass. This may be +nil+.
      # - +body+: The request body with a string that is appropriately encoded
310
      #   (<tt>application/x-www-form-urlencoded</tt> or <tt>multipart/form-data</tt>).
311 312
      # - +session+: A hash of parameters to store in the session. This may be +nil+.
      # - +flash+: A hash of parameters to store in the flash. This may be +nil+.
X
Xavier Noria 已提交
313
      #
314 315
      # You can also simulate POST, PATCH, PUT, DELETE, and HEAD requests with
      # +post+, +patch+, +put+, +delete+, and +head+.
316 317 318 319 320 321
      # Example sending parameters, session and setting a flash message:
      #
      #   get :show,
      #     params: { id: 7 },
      #     session: { user_id: 1 },
      #     flash: { notice: 'This is flash message' }
322 323 324
      #
      # Note that the request method is not verified. The different methods are
      # available to make the tests more expressive.
325
      def get(action, *args)
326
        process_with_kwargs("GET", action, *args)
327 328
      end

329
      # Simulate a POST request with the given parameters and set/volley the response.
X
Xavier Noria 已提交
330
      # See +get+ for more details.
331
      def post(action, *args)
332
        process_with_kwargs("POST", action, *args)
333
      end
334

335
      # Simulate a PATCH request with the given parameters and set/volley the response.
X
Xavier Noria 已提交
336
      # See +get+ for more details.
337
      def patch(action, *args)
338
        process_with_kwargs("PATCH", action, *args)
339 340
      end

341
      # Simulate a PUT request with the given parameters and set/volley the response.
X
Xavier Noria 已提交
342
      # See +get+ for more details.
343
      def put(action, *args)
344
        process_with_kwargs("PUT", action, *args)
345
      end
346

347
      # Simulate a DELETE request with the given parameters and set/volley the response.
X
Xavier Noria 已提交
348
      # See +get+ for more details.
349
      def delete(action, *args)
350
        process_with_kwargs("DELETE", action, *args)
351
      end
352

353
      # Simulate a HEAD request with the given parameters and set/volley the response.
X
Xavier Noria 已提交
354
      # See +get+ for more details.
355
      def head(action, *args)
356
        process_with_kwargs("HEAD", action, *args)
357 358
      end

359
      def xml_http_request(*args)
360 361 362 363 364
        ActiveSupport::Deprecation.warn(<<-MSG.strip_heredoc)
          xhr and xml_http_request methods are deprecated in favor of
          `get :index, xhr: true` and `post :create, xhr: true`
        MSG

365
        @request.env['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
366
        @request.env['HTTP_ACCEPT'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
367
        __send__(*args).tap do
368 369 370 371 372 373
          @request.env.delete 'HTTP_X_REQUESTED_WITH'
          @request.env.delete 'HTTP_ACCEPT'
        end
      end
      alias xhr :xml_http_request

374
      def paramify_values(hash_or_array_or_value)
375 376
        case hash_or_array_or_value
        when Hash
377
          Hash[hash_or_array_or_value.map{|key, value| [key, paramify_values(value)] }]
378
        when Array
379
          hash_or_array_or_value.map {|i| paramify_values(i)}
380
        when Rack::Test::UploadedFile, ActionDispatch::Http::UploadedFile
381
          hash_or_array_or_value
382 383
        else
          hash_or_array_or_value.to_param
384 385 386
        end
      end

387 388 389 390
      # Simulate a HTTP request to +action+ by specifying request method,
      # parameters and set/volley the response.
      #
      # - +action+: The controller action to call.
391 392
      # - +method+: Request method used to send the HTTP request. Possible values
      #   are +GET+, +POST+, +PATCH+, +PUT+, +DELETE+, +HEAD+. Defaults to +GET+. Can be a symbol.
393 394
      # - +params+: The hash with HTTP parameters that you want to pass. This may be +nil+.
      # - +body+: The request body with a string that is appropriately encoded
395
      #   (<tt>application/x-www-form-urlencoded</tt> or <tt>multipart/form-data</tt>).
396 397
      # - +session+: A hash of parameters to store in the session. This may be +nil+.
      # - +flash+: A hash of parameters to store in the flash. This may be +nil+.
398
      # - +format+: Request format. Defaults to +nil+. Can be string or symbol.
399
      #
400
      # Example calling +create+ action and sending two params:
401
      #
402 403 404 405 406 407 408
      #   process :create,
      #     method: 'POST',
      #     params: {
      #       user: { name: 'Gaurish Sharma', email: 'user@example.com' }
      #     },
      #     session: { user_id: 1 },
      #     flash: { notice: 'This is flash message' }
409
      #
410 411 412
      # To simulate +GET+, +POST+, +PATCH+, +PUT+, +DELETE+ and +HEAD+ requests
      # prefer using #get, #post, #patch, #put, #delete and #head methods
      # respectively which will make tests more expressive.
413 414
      #
      # Note that the request method is not verified.
415
      def process(action, *args)
416
        check_required_ivars
A
Aaron Patterson 已提交
417

418
        if kwarg_request?(args)
419
          parameters, session, body, flash, http_method, format, xhr = args[0].values_at(:params, :session, :body, :flash, :method, :format, :xhr)
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
        else
          http_method, parameters, session, flash = args
          format = nil

          if parameters.is_a?(String) && http_method != 'HEAD'
            body = parameters
            parameters = nil
          end

          if parameters.present? || session.present? || flash.present?
            non_kwarg_request_warning
          end
        end

        if body.present?
          @request.env['RAW_POST_DATA'] = body
        end

        if http_method.present?
          http_method = http_method.to_s.upcase
        else
          http_method = "GET"
442
        end
A
Aaron Patterson 已提交
443

444
        parameters ||= {}
A
Aaron Patterson 已提交
445

446
        # Ensure that numbers and symbols passed as params are converted to
447
        # proper params, as is the case when engaging rack.
448
        parameters = paramify_values(parameters) if html_format?(parameters)
449

450 451 452 453
        if format.present?
          parameters[:format] = format
        end

454 455
        @html_document = nil

A
Aaron Patterson 已提交
456 457 458 459
        unless @controller.respond_to?(:recycle!)
          @controller.extend(Testing::Functional)
        end

460 461
        @request.recycle!
        @response.recycle!
A
Aaron Patterson 已提交
462
        @controller.recycle!
463

464
        @request.env['REQUEST_METHOD'] = http_method
465

466
        controller_class_name = @controller.class.anonymous? ?
467
          "anonymous" :
468
          @controller.class.controller_path
469 470

        @request.assign_parameters(@routes, controller_class_name, action.to_s, parameters)
471

472
        @request.session.update(session) if session
473
        @request.flash.update(flash || {})
474

475 476 477 478 479
        if xhr
          @request.env['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
          @request.env['HTTP_ACCEPT'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
        end

480 481 482
        @controller.request  = @request
        @controller.response = @response

483
        build_request_uri(controller_class_name, action, parameters)
484

485
        @controller.recycle!
486
        @controller.process(action)
487

488
        if cookies = @request.env['action_dispatch.cookies']
489
          unless @response.committed?
490 491
            cookies.write(@response)
          end
492 493 494
        end
        @response.prepare!

495
        if flash_value = @request.flash.to_session_value
496
          @request.session['flash'] = flash_value
497 498
        else
          @request.session.delete('flash')
499 500
        end

501 502 503 504 505
        if xhr
          @request.env.delete 'HTTP_X_REQUESTED_WITH'
          @request.env.delete 'HTTP_ACCEPT'
        end

506
        @response
507 508
      end

509
      def setup_controller_request_and_response
510 511
        @controller = nil unless defined? @controller

512 513
        response_klass = TestResponse

514
        if klass = self.class.controller_class
515 516 517
          if klass < ActionController::Live
            response_klass = LiveTestResponse
          end
518 519 520 521 522 523 524
          unless @controller
            begin
              @controller = klass.new
            rescue
              warn "could not construct controller #{klass}" if $VERBOSE
            end
          end
525
        end
526

527 528 529 530
        @request          = build_request
        @response         = build_response response_klass
        @response.request = @request

531
        if @controller
532 533 534
          @controller.request = @request
          @controller.params = {}
        end
535 536
      end

537 538 539 540
      def build_request
        TestRequest.new
      end

541 542
      def build_response(klass)
        klass.new
543 544
      end

545 546 547
      included do
        include ActionController::TemplateAssertions
        include ActionDispatch::Assertions
548
        class_attribute :_controller_class
549 550
        setup :setup_controller_request_and_response
      end
551

A
Aaron Patterson 已提交
552
      private
553

554
      def process_with_kwargs(http_method, action, *args)
555
        if kwarg_request?(args)
556 557 558 559 560 561 562 563 564 565
          args.first.merge!(method: http_method)
          process(action, *args)
        else
          non_kwarg_request_warning if args.present?

          args = args.unshift(http_method)
          process(action, *args)
        end
      end

566
      REQUEST_KWARGS = %i(params session flash method body xhr)
567
      def kwarg_request?(args)
568 569 570 571 572 573 574 575 576 577 578 579 580 581
        args[0].respond_to?(:keys) && (
          (args[0].key?(:format) && args[0].keys.size == 1) ||
          args[0].keys.any? { |k| REQUEST_KWARGS.include?(k) }
        )
      end

      def non_kwarg_request_warning
        ActiveSupport::Deprecation.warn(<<-MSG.strip_heredoc)
          ActionController::TestCase HTTP request methods will accept only
          keyword arguments in future Rails versions.

          Examples:

          get :show, params: { id: 1 }, session: { user_id: 1 }
582
          process :update, method: :post, params: { id: 1 }
583 584 585
        MSG
      end

586 587 588 589
      def document_root_element
        html_document.root
      end

590 591 592
      def check_required_ivars
        # Sanity check for required instance variables so we can give an
        # understandable error message.
593 594
        [:@routes, :@controller, :@request, :@response].each do |iv_name|
          if !instance_variable_defined?(iv_name) || instance_variable_get(iv_name).nil?
595 596 597 598
            raise "#{iv_name} is nil: make sure you set it in your test's setup method."
          end
        end
      end
A
Aaron Patterson 已提交
599

600
      def build_request_uri(controller_class_name, action, parameters)
601
        unless @request.env["PATH_INFO"]
602
          options = @controller.respond_to?(:url_options) ? @controller.__send__(:url_options).merge(parameters) : parameters
603
          options.update(
604
            :controller => controller_class_name,
605 606
            :action => action,
            :relative_url_root => nil,
607
            :_recall => @request.path_parameters)
608

609
          url, query_string = @routes.path_for(options).split("?", 2)
610 611 612 613 614

          @request.env["SCRIPT_NAME"] = @controller.config.relative_url_root
          @request.env["PATH_INFO"] = url
          @request.env["QUERY_STRING"] = query_string || ""
        end
615
      end
616 617

      def html_format?(parameters)
618
        return true unless parameters.key?(:format)
619
        Mime.fetch(parameters[:format]) { Mime['html'] }.html?
620
      end
621
    end
622 623 624

    include Behavior
  end
P
Pratik Naik 已提交
625
end