test_case.rb 21.6 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 self.new_session
      TestSession.new
    end

17 18 19 20
    # Create a new test request with default `env` values
    def self.create
      env = {}
      env = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application
21
      env["rack.request.cookie_hash"] = {}.with_indifferent_access
22 23 24 25 26 27 28 29
      new(default_env.merge(env), new_session)
    end

    def self.default_env
      DEFAULT_ENV
    end
    private_class_method :default_env

30 31
    def initialize(env, session)
      super(env)
32

33
      self.session = session
34
      self.session_options = TestSession::DEFAULT_OPTIONS
35 36
    end

37 38
    def query_string=(string)
      @env[Rack::QUERY_STRING] = string
39 40 41 42 43 44
    end

    def request_parameters=(params)
      @env["action_dispatch.request.request_parameters"] = params
    end

J
Joshua Peek 已提交
45
    def assign_parameters(routes, controller_path, action, parameters = {})
46 47
      parameters = parameters.symbolize_keys
      extra_keys = routes.extra_keys(parameters.merge(:controller => controller_path, :action => action))
A
Aaron Patterson 已提交
48
      non_path_parameters = {}
49
      path_parameters = {}
50

51
      parameters.each do |key, value|
52
        if extra_keys.include?(key) || key == :action || key == :controller
53 54
          non_path_parameters[key] = value
        else
55
          if value.is_a?(Array)
56
            value = value.map(&:to_param)
57 58 59 60
          else
            value = value.to_param
          end

61
          path_parameters[key] = value
62 63 64
        end
      end

65
      if get?
66 67 68
        if self.query_string.blank?
          self.query_string = non_path_parameters.to_query
        end
69
      else
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
        if ENCODER.should_multipart?(non_path_parameters)
          @env['CONTENT_TYPE'] = ENCODER.content_type
          data = ENCODER.build_multipart non_path_parameters
        else
          @env['CONTENT_TYPE'] ||= 'application/x-www-form-urlencoded'

          # FIXME: setting `request_parametes` is normally handled by the
          # params parser middleware, and we should remove this roundtripping
          # when we switch to caling `call` on the controller

          case content_mime_type.ref
          when :json
            data = ActiveSupport::JSON.encode(non_path_parameters)
            params = ActiveSupport::JSON.decode(data).with_indifferent_access
            self.request_parameters = params
          when :xml
            data = non_path_parameters.to_xml
            params = Hash.from_xml(data)['hash']
            self.request_parameters = params
          when :url_encoded_form
            data = non_path_parameters.to_query
          else
            raise "Unknown Content-Type: #{content_type}"
          end
        end
95 96 97

        @env['CONTENT_LENGTH'] = data.length.to_s
        @env['rack.input'] = StringIO.new(data)
98 99
      end

100 101 102
      path_parameters[:controller] = controller_path
      path_parameters[:action] = action

103
      self.path_parameters = path_parameters
104
    end
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131

    ENCODER = Class.new do
      include Rack::Test::Utils

      def should_multipart?(params)
        # FIXME: lifted from Rack-Test. We should push this separation upstream
        multipart = false
        query = lambda { |value|
          case value
          when Array
            value.each(&query)
          when Hash
            value.values.each(&query)
          when Rack::Test::UploadedFile
            multipart = true
          end
        }
        params.values.each(&query)
        multipart
      end

      public :build_multipart

      def content_type
        "multipart/form-data; boundary=#{Rack::Test::MULTIPART_BOUNDARY}"
      end
    end.new
132 133 134 135 136
  end

  class TestResponse < ActionDispatch::TestResponse
  end

137 138 139 140
  class LiveTestResponse < Live::Response
    def body
      @body ||= super
    end
141 142 143 144 145 146 147 148 149 150 151 152

    # 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?
153 154
  end

155 156
  # Methods #destroy and #load! are overridden to avoid calling methods on the
  # @store object, which does not exist for the TestSession class.
157 158
  class TestSession < Rack::Session::Abstract::SessionHash #:nodoc:
    DEFAULT_OPTIONS = Rack::Session::Abstract::ID::DEFAULT_OPTIONS
159 160

    def initialize(session = {})
161
      super(nil, nil)
162 163
      @id = SecureRandom.hex(16)
      @data = stringify_keys(session)
164 165
      @loaded = true
    end
166

167 168 169
    def exists?
      true
    end
170

171 172 173 174 175 176 177 178
    def keys
      @data.keys
    end

    def values
      @data.values
    end

179 180 181 182 183 184 185 186 187
    def destroy
      clear
    end

    private

      def load!
        @id
      end
188 189
  end

P
Pratik Naik 已提交
190 191
  # Superclass for ActionController functional tests. Functional tests allow you to
  # test a single controller action per test method. This should not be confused with
192
  # integration tests (see ActionDispatch::IntegrationTest), which are more like
193
  # "stories" that can involve multiple controllers and multiple actions (i.e. multiple
P
Pratik Naik 已提交
194
  # different HTTP requests).
P
Pratik Naik 已提交
195
  #
P
Pratik Naik 已提交
196 197 198
  # == Basic example
  #
  # Functional tests are written as follows:
199
  # 1. First, one uses the +get+, +post+, +patch+, +put+, +delete+ or +head+ method to simulate
P
Pratik Naik 已提交
200 201 202 203 204 205 206 207 208
  #    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.
209
  #       post(:create, params: { book: { title: "Love Hina" }})
P
Pratik Naik 已提交
210 211 212 213 214 215
  #
  #       # 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.
216
  #       assert_not_nil Book.find_by(title: "Love Hina")
P
Pratik Naik 已提交
217 218 219
  #     end
  #   end
  #
220 221 222
  # You can also send a real document in the simulated HTTP request.
  #
  #   def test_create
A
AvnerCohen 已提交
223
  #     json = {book: { title: "Love Hina" }}.to_json
224
  #     post :create, json
R
Rafael Mendonça França 已提交
225
  #   end
226
  #
P
Pratik Naik 已提交
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
  # == 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 已提交
244
  # (Earlier versions of \Rails required each functional test to subclass
P
Pratik Naik 已提交
245
  # Test::Unit::TestCase and define @controller, @request, @response in +setup+.)
P
Pratik Naik 已提交
246
  #
P
Pratik Naik 已提交
247
  # == Controller is automatically inferred
P
Pratik Naik 已提交
248
  #
P
Pratik Naik 已提交
249 250
  # 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 已提交
251
  # class name, you can explicitly set it with +tests+.
P
Pratik Naik 已提交
252 253 254 255
  #
  #   class SpecialEdgeCaseWidgetsControllerTest < ActionController::TestCase
  #     tests WidgetController
  #   end
256
  #
J
Joost Baaij 已提交
257
  # == \Testing controller internals
258 259 260 261 262 263
  #
  # 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:
  #
  # * session: Objects being saved in the session.
  # * flash: The flash objects currently in the session.
J
Joost Baaij 已提交
264
  # * cookies: \Cookies being sent to the user on this request.
265 266 267 268 269 270
  #
  # These collections can be used just like any other hash:
  #
  #   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
  #
271
  # On top of the collections, you have the complete url that a given action redirected to available in <tt>redirect_to_url</tt>.
272 273 274 275
  #
  # 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.
  #
276
  # == Manipulating session and cookie variables
277
  #
278 279
  # 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:
280
  #
281 282
  #   session[:key] = "value"
  #   cookies[:key] = "value"
283
  #
284
  # To clear the cookies for a test just clear the cookie collection:
285
  #
286
  #   cookies.clear
287
  #
J
Joost Baaij 已提交
288
  # == \Testing named routes
289 290 291
  #
  # If you're using named routes, they can be easily tested using the original named routes' methods straight in the test case.
  #
A
AvnerCohen 已提交
292
  #  assert_redirected_to page_url(title: 'foo')
293
  class TestCase < ActiveSupport::TestCase
294 295 296
    module Behavior
      extend ActiveSupport::Concern
      include ActionDispatch::TestProcess
297
      include ActiveSupport::Testing::ConstantLookup
298
      include Rails::Dom::Testing::Assertions
299

300
      attr_reader :response, :request
301

302
      module ClassMethods
303

304
        # Sets the controller class name. Useful if the name can't be inferred from test class.
305
        # Normalizes +controller_class+ before using.
306 307 308 309
        #
        #   tests WidgetController
        #   tests :widget
        #   tests 'widget'
310
        def tests(controller_class)
311 312
          case controller_class
          when String, Symbol
313
            self.controller_class = "#{controller_class.to_s.camelize}Controller".constantize
314 315 316 317 318
          when Class
            self.controller_class = controller_class
          else
            raise ArgumentError, "controller class must be a String, Symbol, or Class"
          end
319
        end
320

321
        def controller_class=(new_class)
322
          self._controller_class = new_class
323
        end
324

325
        def controller_class
326
          if current_controller_class = self._controller_class
327 328 329 330 331
            current_controller_class
          else
            self.controller_class = determine_default_controller_class(name)
          end
        end
332

333
        def determine_default_controller_class(name)
334 335 336
          determine_constant_from_test_name(name) do |constant|
            Class === constant && constant < ActionController::Metal
          end
337
        end
338
      end
339

340 341
      # Simulate a GET request with the given parameters.
      #
342
      # - +action+: The controller action to call.
343 344
      # - +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
345
      #   (<tt>application/x-www-form-urlencoded</tt> or <tt>multipart/form-data</tt>).
346 347
      # - +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 已提交
348
      #
349 350
      # You can also simulate POST, PATCH, PUT, DELETE, and HEAD requests with
      # +post+, +patch+, +put+, +delete+, and +head+.
351 352 353 354 355 356
      # Example sending parameters, session and setting a flash message:
      #
      #   get :show,
      #     params: { id: 7 },
      #     session: { user_id: 1 },
      #     flash: { notice: 'This is flash message' }
357 358 359
      #
      # Note that the request method is not verified. The different methods are
      # available to make the tests more expressive.
360
      def get(action, *args)
E
eileencodes 已提交
361 362 363
        res = process_with_kwargs("GET", action, *args)
        cookies.update res.cookies
        res
364 365
      end

366
      # Simulate a POST request with the given parameters and set/volley the response.
X
Xavier Noria 已提交
367
      # See +get+ for more details.
368
      def post(action, *args)
369
        process_with_kwargs("POST", action, *args)
370
      end
371

372
      # Simulate a PATCH request with the given parameters and set/volley the response.
X
Xavier Noria 已提交
373
      # See +get+ for more details.
374
      def patch(action, *args)
375
        process_with_kwargs("PATCH", action, *args)
376 377
      end

378
      # Simulate a PUT request with the given parameters and set/volley the response.
X
Xavier Noria 已提交
379
      # See +get+ for more details.
380
      def put(action, *args)
381
        process_with_kwargs("PUT", action, *args)
382
      end
383

384
      # Simulate a DELETE request with the given parameters and set/volley the response.
X
Xavier Noria 已提交
385
      # See +get+ for more details.
386
      def delete(action, *args)
387
        process_with_kwargs("DELETE", action, *args)
388
      end
389

390
      # Simulate a HEAD request with the given parameters and set/volley the response.
X
Xavier Noria 已提交
391
      # See +get+ for more details.
392
      def head(action, *args)
393
        process_with_kwargs("HEAD", action, *args)
394 395
      end

396
      def xml_http_request(*args)
397 398 399 400 401
        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

402
        @request.env['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
403
        @request.env['HTTP_ACCEPT'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
404
        __send__(*args).tap do
405 406 407 408 409 410
          @request.env.delete 'HTTP_X_REQUESTED_WITH'
          @request.env.delete 'HTTP_ACCEPT'
        end
      end
      alias xhr :xml_http_request

411 412 413 414
      # Simulate a HTTP request to +action+ by specifying request method,
      # parameters and set/volley the response.
      #
      # - +action+: The controller action to call.
415 416
      # - +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.
417 418
      # - +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
419
      #   (<tt>application/x-www-form-urlencoded</tt> or <tt>multipart/form-data</tt>).
420 421
      # - +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+.
422
      # - +format+: Request format. Defaults to +nil+. Can be string or symbol.
423
      #
424
      # Example calling +create+ action and sending two params:
425
      #
426 427 428 429 430 431 432
      #   process :create,
      #     method: 'POST',
      #     params: {
      #       user: { name: 'Gaurish Sharma', email: 'user@example.com' }
      #     },
      #     session: { user_id: 1 },
      #     flash: { notice: 'This is flash message' }
433
      #
434 435 436
      # 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.
437 438
      #
      # Note that the request method is not verified.
439
      def process(action, *args)
440
        check_required_ivars
A
Aaron Patterson 已提交
441

442
        if kwarg_request?(args)
443
          parameters, session, body, flash, http_method, format, xhr = args[0].values_at(:params, :session, :body, :flash, :method, :format, :xhr)
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
        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"
466
        end
A
Aaron Patterson 已提交
467

468
        parameters ||= {}
A
Aaron Patterson 已提交
469

470 471 472 473
        if format.present?
          parameters[:format] = format
        end

474 475
        @html_document = nil

A
Aaron Patterson 已提交
476 477 478 479
        unless @controller.respond_to?(:recycle!)
          @controller.extend(Testing::Functional)
        end

480 481 482 483
        self.cookies.update @request.cookies
        @request.env['HTTP_COOKIE'] = cookies.to_header
        @request.env['action_dispatch.cookies'] = nil

484
        @request          = TestRequest.new scrub_env!(@request.env), @request.session
485 486
        @response         = build_response @response_klass
        @response.request = @request
A
Aaron Patterson 已提交
487
        @controller.recycle!
488

489
        @request.env['REQUEST_METHOD'] = http_method
490

491
        controller_class_name = @controller.class.anonymous? ?
492
          "anonymous" :
493
          @controller.class.controller_path
494 495

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

497
        @request.session.update(session) if session
498
        @request.flash.update(flash || {})
499

500 501 502 503 504
        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

505 506 507
        @controller.request  = @request
        @controller.response = @response

508
        build_request_uri(controller_class_name, action, parameters)
509

510
        @controller.recycle!
511
        @controller.process(action)
512

513 514
        @request.env.delete 'HTTP_COOKIE'

515
        if cookies = @request.env['action_dispatch.cookies']
516
          unless @response.committed?
517
            cookies.write(@response)
E
eileencodes 已提交
518
            self.cookies.update(cookies.instance_variable_get(:@cookies))
519
          end
520 521 522
        end
        @response.prepare!

523
        if flash_value = @request.flash.to_session_value
524
          @request.session['flash'] = flash_value
525 526
        else
          @request.session.delete('flash')
527 528
        end

529 530 531 532
        if xhr
          @request.env.delete 'HTTP_X_REQUESTED_WITH'
          @request.env.delete 'HTTP_ACCEPT'
        end
533
        @request.query_string = ''
534

535
        @response
536 537
      end

538
      def setup_controller_request_and_response
539 540
        @controller = nil unless defined? @controller

541
        @response_klass = TestResponse
542

543
        if klass = self.class.controller_class
544
          if klass < ActionController::Live
545
            @response_klass = LiveTestResponse
546
          end
547 548 549 550 551 552 553
          unless @controller
            begin
              @controller = klass.new
            rescue
              warn "could not construct controller #{klass}" if $VERBOSE
            end
          end
554
        end
555

556
        @request          = TestRequest.create
557
        @response         = build_response @response_klass
558 559
        @response.request = @request

560
        if @controller
561 562 563
          @controller.request = @request
          @controller.params = {}
        end
564 565
      end

566 567
      def build_response(klass)
        klass.new
568 569
      end

570 571 572
      included do
        include ActionController::TemplateAssertions
        include ActionDispatch::Assertions
573
        class_attribute :_controller_class
574 575
        setup :setup_controller_request_and_response
      end
576

A
Aaron Patterson 已提交
577
      private
578

579 580 581
      def scrub_env!(env)
        env.delete_if { |k, v| k =~ /^(action_dispatch|rack)\.request/ }
        env.delete_if { |k, v| k =~ /^action_dispatch\.rescue/ }
582
        env.delete 'action_dispatch.request.query_parameters'
583
        env.delete 'action_dispatch.request.request_parameters'
584 585 586
        env
      end

587
      def process_with_kwargs(http_method, action, *args)
588
        if kwarg_request?(args)
589 590 591
          args.first.merge!(method: http_method)
          process(action, *args)
        else
592
          non_kwarg_request_warning if args.any?
593 594 595 596 597 598

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

599
      REQUEST_KWARGS = %i(params session flash method body xhr)
600
      def kwarg_request?(args)
601 602 603 604 605 606 607 608 609 610 611 612 613 614
        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 }
615
          process :update, method: :post, params: { id: 1 }
616 617 618
        MSG
      end

619 620 621 622
      def document_root_element
        html_document.root
      end

623 624 625
      def check_required_ivars
        # Sanity check for required instance variables so we can give an
        # understandable error message.
626 627
        [:@routes, :@controller, :@request, :@response].each do |iv_name|
          if !instance_variable_defined?(iv_name) || instance_variable_get(iv_name).nil?
628 629 630 631
            raise "#{iv_name} is nil: make sure you set it in your test's setup method."
          end
        end
      end
A
Aaron Patterson 已提交
632

633
      def build_request_uri(controller_class_name, action, parameters)
634
        unless @request.env["PATH_INFO"]
635
          options = @controller.respond_to?(:url_options) ? @controller.__send__(:url_options).merge(parameters) : parameters
636
          options.update(
637
            :controller => controller_class_name,
638 639
            :action => action,
            :relative_url_root => nil,
640
            :_recall => @request.path_parameters)
641

642
          url, = @routes.path_for(options).split("?", 2)
643 644 645

          @request.env["PATH_INFO"] = url
        end
646
        @request.env["SCRIPT_NAME"] ||= @controller.config.relative_url_root
647
      end
648 649

      def html_format?(parameters)
650
        return true unless parameters.key?(:format)
651
        Mime.fetch(parameters[:format]) { Mime['html'] }.html?
652
      end
653
    end
654 655 656

    include Behavior
  end
P
Pratik Naik 已提交
657
end