integration.rb 26.2 KB
Newer Older
1 2
require 'stringio'
require 'uri'
3
require 'active_support/core_ext/kernel/singleton_class'
4
require 'active_support/core_ext/object/try'
5
require 'active_support/core_ext/string/strip'
J
Joshua Peek 已提交
6
require 'rack/test'
7
require 'minitest'
8 9

module ActionDispatch
D
David Heinemeier Hansson 已提交
10
  module Integration #:nodoc:
11 12 13 14 15
    module RequestHelpers
      # Performs a GET request with the given parameters.
      #
      # - +path+: The URI (as a String) on which you want to perform a GET
      #   request.
16
      # - +params+: The HTTP parameters that you want to pass. This may
17 18 19 20
      #   be +nil+,
      #   a Hash, or a String that is appropriately encoded
      #   (<tt>application/x-www-form-urlencoded</tt> or
      #   <tt>multipart/form-data</tt>).
21
      # - +headers+: Additional headers to pass, as a Hash. The headers will be
22
      #   merged into the Rack env hash.
23
      # - +env+: Additional env to pass, as a Hash. The headers will be
24
      #   merged into the Rack env hash.
25
      #
R
Robin Dupret 已提交
26
      # This method returns a Response object, which one can use to
27
      # inspect the details of the response. Furthermore, if this method was
28
      # called from an ActionDispatch::IntegrationTest object, then that
29 30 31
      # object's <tt>@response</tt> instance variable will point to the same
      # response object.
      #
32 33
      # You can also perform POST, PATCH, PUT, DELETE, and HEAD requests with
      # +#post+, +#patch+, +#put+, +#delete+, and +#head+.
34 35 36 37
      #
      # Example:
      #
      #   get '/feed', params: { since: 201501011400 }
38
      #   post '/profile', headers: { "X-Test-Header" => "testvalue" }
39 40
      def get(path, *args)
        process_with_kwargs(:get, path, *args)
41 42
      end

43
      # Performs a POST request with the given parameters. See +#get+ for more
44
      # details.
45 46
      def post(path, *args)
        process_with_kwargs(:post, path, *args)
47 48
      end

49 50
      # Performs a PATCH request with the given parameters. See +#get+ for more
      # details.
51 52
      def patch(path, *args)
        process_with_kwargs(:patch, path, *args)
53 54
      end

55
      # Performs a PUT request with the given parameters. See +#get+ for more
56
      # details.
57 58
      def put(path, *args)
        process_with_kwargs(:put, path, *args)
59 60
      end

61
      # Performs a DELETE request with the given parameters. See +#get+ for
62
      # more details.
63 64
      def delete(path, *args)
        process_with_kwargs(:delete, path, *args)
65 66
      end

67
      # Performs a HEAD request with the given parameters. See +#get+ for more
68
      # details.
69 70
      def head(path, *args)
        process_with_kwargs(:head, path, *args)
71 72 73
      end

      # Performs an XMLHttpRequest request with the given parameters, mirroring
S
Sean Griffin 已提交
74
      # an AJAX request made from JavaScript.
75
      #
76 77
      # The request_method is +:get+, +:post+, +:patch+, +:put+, +:delete+ or
      # +:head+; the parameters are +nil+, a hash, or a url-encoded or multipart
78
      # string; the headers are a hash.
79 80 81 82 83
      #
      # Example:
      #
      #   xhr :get, '/feed', params: { since: 201501011400 }
      def xml_http_request(request_method, path, *args)
84
        if kwarg_request?(args)
85 86 87 88 89 90 91 92 93 94 95
          params, headers, env = args.first.values_at(:params, :headers, :env)
        else
          params = args[0]
          headers = args[1]
          env = {}

          if params.present? || headers.present?
            non_kwarg_request_warning
          end
        end

96 97
        ActiveSupport::Deprecation.warn(<<-MSG.strip_heredoc)
          xhr and xml_http_request methods are deprecated in favor of
98
          `get "/posts", xhr: true` and `post "/posts/1", xhr: true`.
99 100 101
        MSG

        process(request_method, path, params: params, headers: headers, xhr: true)
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
      end
      alias xhr :xml_http_request

      # Follow a single redirect response. If the last response was not a
      # redirect, an exception will be raised. Otherwise, the redirect is
      # performed on the location header.
      def follow_redirect!
        raise "not a redirect! #{status} #{status_message}" unless redirect?
        get(response.location)
        status
      end

      # Performs a request using the specified method, following any subsequent
      # redirect. Note that the redirects are followed until the response is
      # not a redirect--this means you may run into an infinite loop if your
      # redirect loops back to itself.
118 119 120 121 122
      #
      # Example:
      #
      #   request_via_redirect :post, '/welcome',
      #     params: { ref_id: 14 },
123
      #     headers: { "X-Test-Header" => "testvalue" }
124
      def request_via_redirect(http_method, path, *args)
125
        ActiveSupport::Deprecation.warn('`request_via_redirect` is deprecated and will be removed in Rails 5.1. Please use `follow_redirect!` manually after the request call for the same behavior.')
126 127
        process_with_kwargs(http_method, path, *args)

128 129 130 131 132 133
        follow_redirect! while redirect?
        status
      end

      # Performs a GET request, following any subsequent redirect.
      # See +request_via_redirect+ for more information.
134
      def get_via_redirect(path, *args)
135
        ActiveSupport::Deprecation.warn('`get_via_redirect` is deprecated and will be removed in Rails 5.1. Please use `follow_redirect!` manually after the request call for the same behavior.')
136
        request_via_redirect(:get, path, *args)
137 138 139 140
      end

      # Performs a POST request, following any subsequent redirect.
      # See +request_via_redirect+ for more information.
141
      def post_via_redirect(path, *args)
142
        ActiveSupport::Deprecation.warn('`post_via_redirect` is deprecated and will be removed in Rails 5.1. Please use `follow_redirect!` manually after the request call for the same behavior.')
143
        request_via_redirect(:post, path, *args)
144 145
      end

146 147
      # Performs a PATCH request, following any subsequent redirect.
      # See +request_via_redirect+ for more information.
148
      def patch_via_redirect(path, *args)
149
        ActiveSupport::Deprecation.warn('`patch_via_redirect` is deprecated and will be removed in Rails 5.1. Please use `follow_redirect!` manually after the request call for the same behavior.')
150
        request_via_redirect(:patch, path, *args)
151 152
      end

153 154
      # Performs a PUT request, following any subsequent redirect.
      # See +request_via_redirect+ for more information.
155
      def put_via_redirect(path, *args)
156
        ActiveSupport::Deprecation.warn('`put_via_redirect` is deprecated and will be removed in Rails 5.1. Please use `follow_redirect!` manually after the request call for the same behavior.')
157
        request_via_redirect(:put, path, *args)
158 159 160 161
      end

      # Performs a DELETE request, following any subsequent redirect.
      # See +request_via_redirect+ for more information.
162
      def delete_via_redirect(path, *args)
163
        ActiveSupport::Deprecation.warn('`delete_via_redirect` is deprecated and will be removed in Rails 5.1. Please use `follow_redirect!` manually after the request call for the same behavior.')
164
        request_via_redirect(:delete, path, *args)
165 166 167
      end
    end

168 169
    # An instance of this class represents a set of requests and responses
    # performed sequentially by a test process. Because you can instantiate
170 171 172
    # multiple sessions and run them side-by-side, you can also mimic (to some
    # limited extent) multiple simultaneous users interacting with your system.
    #
173 174 175
    # Typically, you will instantiate a new session using
    # IntegrationTest#open_session, rather than instantiating
    # Integration::Session directly.
176
    class Session
177 178
      DEFAULT_HOST = "www.example.com"

179
      include Minitest::Assertions
J
Joshua Peek 已提交
180
      include TestProcess, RequestHelpers, Assertions
181

182 183 184
      %w( status status_message headers body redirect? ).each do |method|
        delegate method, :to => :response, :allow_nil => true
      end
185

186 187 188
      %w( path ).each do |method|
        delegate method, :to => :request, :allow_nil => true
      end
189 190

      # The hostname used in the last request.
191 192 193 194
      def host
        @host || DEFAULT_HOST
      end
      attr_writer :host
195 196 197

      # The remote_addr used in the last request.
      attr_accessor :remote_addr
198

199 200 201
      # The Accept header to send.
      attr_accessor :accept

202 203
      # A map of the cookies returned by the last response, and which will be
      # sent with the next request.
204
      def cookies
205
        _mock_session.cookie_jar
206
      end
207 208 209 210 211 212 213 214 215 216

      # A reference to the controller instance used by the last request.
      attr_reader :controller

      # A reference to the request instance used by the last request.
      attr_reader :request

      # A reference to the response instance used by the last request.
      attr_reader :response

217 218 219
      # A running counter of the number of requests processed.
      attr_accessor :request_count

220 221
      include ActionDispatch::Routing::UrlFor

P
Pratik Naik 已提交
222
      # Create and initialize a new Session instance.
223
      def initialize(app)
J
José Valim 已提交
224
        super()
225
        @app = app
226

227 228 229
        reset!
      end

230 231 232 233
      def url_options
        @url_options ||= default_url_options.dup.tap do |url_options|
          url_options.reverse_merge!(controller.url_options) if controller

234
          if @app.respond_to?(:routes)
235 236 237 238 239
            url_options.reverse_merge!(@app.routes.default_url_options)
          end

          url_options.reverse_merge!(:host => host, :protocol => https? ? "https" : "http")
        end
240 241
      end

242 243 244 245 246 247 248 249
      # Resets the instance. This can be used to reset the state information
      # in an existing session instance, so it can be used from a clean-slate
      # condition.
      #
      #   session.reset!
      def reset!
        @https = false
        @controller = @request = @response = nil
250
        @_mock_session = nil
251
        @request_count = 0
252
        @url_options = nil
253

254
        self.host        = DEFAULT_HOST
255
        self.remote_addr = "127.0.0.1"
256 257 258
        self.accept      = "text/xml,application/xml,application/xhtml+xml," +
                           "text/html;q=0.9,text/plain;q=0.8,image/png," +
                           "*/*;q=0.5"
J
Jamis Buck 已提交
259

260
        unless defined? @named_routes_configured
J
Jamis Buck 已提交
261 262 263 264
          # the helpers are made protected by default--we make them public for
          # easier access during testing and troubleshooting.
          @named_routes_configured = true
        end
265 266 267 268 269 270
      end

      # Specify whether or not the session should mimic a secure HTTPS request.
      #
      #   session.https!
      #   session.https!(false)
271
      def https!(flag = true)
272
        @https = flag
273 274
      end

275
      # Returns +true+ if the session is mimicking a secure HTTPS request.
276 277 278 279 280 281 282 283 284 285
      #
      #   if session.https?
      #     ...
      #   end
      def https?
        @https
      end

      # Set the host name to use in the next request.
      #
286
      #   session.host! "www.example.com"
A
Aaron Patterson 已提交
287
      alias :host! :host=
288 289

      private
290 291 292
        def _mock_session
          @_mock_session ||= Rack::MockSession.new(@app, host)
        end
293

294
        def process_with_kwargs(http_method, path, *args)
295
          if kwarg_request?(args)
296 297
            process(http_method, path, *args)
          else
298
            non_kwarg_request_warning if args.any?
299 300 301 302
            process(http_method, path, { params: args[0], headers: args[1] })
          end
        end

303
        REQUEST_KWARGS = %i(params headers env xhr as)
304
        def kwarg_request?(args)
305 306 307 308 309
          args[0].respond_to?(:keys) && args[0].keys.any? { |k| REQUEST_KWARGS.include?(k) }
        end

        def non_kwarg_request_warning
          ActiveSupport::Deprecation.warn(<<-MSG.strip_heredoc)
310
            ActionDispatch::IntegrationTest HTTP request methods will accept only
G
Guo Xiang Tan 已提交
311 312
            the following keyword arguments in future Rails versions:
            #{REQUEST_KWARGS.join(', ')}
313 314 315 316 317 318

            Examples:

            get '/profile',
              params: { id: 1 },
              headers: { 'X-Extra-Header' => '123' },
A
Arthur Neves 已提交
319
              env: { 'action_dispatch.custom' => 'custom' },
320 321
              xhr: true,
              as: :json
322 323 324
          MSG
        end

325
        # Performs the actual request.
326 327 328
        def process(method, path, params: nil, headers: nil, env: nil, xhr: false, as: nil)
          request_encoder = RequestEncoder.encoder(as)

329 330 331
          if path =~ %r{://}
            location = URI.parse(path)
            https! URI::HTTPS === location if location.scheme
332 333 334 335 336
            if url_host = location.host
              default = Rack::Request::DEFAULT_PORTS[location.scheme]
              url_host += ":#{location.port}" if default != location.port
              host! url_host
            end
337 338
            path = request_encoder.append_format_to location.path
            path = location.query ? "#{path}?#{location.query}" : path
K
Kasper Timm Hansen 已提交
339
          elsif as
340 341 342
            location = URI.parse(path)
            path = request_encoder.append_format_to location.path
            path = location.query ? "#{path}?#{location.query}" : path
343
          end
344

345
          hostname, port = host.split(':')
346

347
          request_env = {
348
            :method => method,
349
            :params => request_encoder.encode_params(params),
350

351
            "SERVER_NAME"     => hostname,
352
            "SERVER_PORT"     => port || (https? ? "443" : "80"),
353 354 355
            "HTTPS"           => https? ? "on" : "off",
            "rack.url_scheme" => https? ? "https" : "http",

356
            "REQUEST_URI"    => path,
357
            "HTTP_HOST"      => host,
358
            "REMOTE_ADDR"    => remote_addr,
359
            "CONTENT_TYPE"   => request_encoder.content_type,
360
            "HTTP_ACCEPT"    => accept
361
          }
362 363 364 365

          if xhr
            headers ||= {}
            headers['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
366
            headers['HTTP_ACCEPT'] ||= [Mime[:js], Mime[:html], Mime[:xml], 'text/xml', '*/*'].join(', ')
367 368
          end

369 370
          # this modifies the passed request_env directly
          if headers.present?
371
            Http::Headers.from_hash(request_env).merge!(headers)
372 373
          end
          if env.present?
374
            Http::Headers.from_hash(request_env).merge!(env)
375
          end
376

377
          session = Rack::Test::Session.new(_mock_session)
378

379 380
          # NOTE: rack-test v0.5 doesn't build a default uri correctly
          # Make sure requested path is always a full uri
381
          session.request(build_full_uri(path, request_env), request_env)
382

383
          @request_count += 1
384
          @request  = ActionDispatch::Request.new(session.last_request.env)
385
          response = _mock_session.last_response
386
          @response = ActionDispatch::TestResponse.from_response(response)
E
eileencodes 已提交
387
          @response.request = @request
388
          @response.response_parser = RequestEncoder.parser(@response.content_type)
389
          @html_document = nil
390
          @url_options = nil
391

392
          @controller = @request.controller_instance
393

394
          response.status
395
        end
396 397 398 399

        def build_full_uri(path, env)
          "#{env['rack.url_scheme']}://#{env['SERVER_NAME']}:#{env['SERVER_PORT']}#{path}"
        end
400 401 402 403

        class RequestEncoder # :nodoc:
          @encoders = {}

404 405
          attr_reader :response_parser

406
          def initialize(mime_name, param_encoder, response_parser, url_encoded_form = false)
407 408 409 410 411 412 413 414 415
            @mime = Mime[mime_name]

            unless @mime
              raise ArgumentError, "Can't register a request encoder for " \
                "unregistered MIME Type: #{mime_name}. See `Mime::Type.register`."
            end

            @url_encoded_form = url_encoded_form
            @path_format      = ".#{@mime.symbol}" unless @url_encoded_form
416 417
            @response_parser  = response_parser || -> body { body }
            @param_encoder    = param_encoder   || :"to_#{@mime.symbol}".to_proc
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
          end

          def append_format_to(path)
            path << @path_format unless @url_encoded_form
            path
          end

          def content_type
            @mime.to_s
          end

          def encode_params(params)
            @param_encoder.call(params)
          end

433 434 435
          def self.parser(content_type)
            mime = Mime::Type.lookup(content_type)
            encoder(mime ? mime.ref : nil).response_parser
436 437
          end

438 439 440 441
          def self.encoder(name)
            @encoders[name] || WWWFormEncoder
          end

442 443
          def self.register_encoder(mime_name, param_encoder: nil, response_parser: nil)
            @encoders[mime_name] = new(mime_name, param_encoder, response_parser)
444 445
          end

446
          register_encoder :json, response_parser: -> body { JSON.parse(body) }
447

448
          WWWFormEncoder = new(:url_encoded_form, -> params { params }, nil, true)
449
        end
450 451
    end

452
    module Runner
453 454
      include ActionDispatch::Assertions

455 456
      APP_SESSIONS = {}

457 458
      attr_reader :app

459
      def before_setup # :nodoc:
460 461
        @app = nil
        @integration_session = nil
E
eileencodes 已提交
462
        super
463 464 465
      end

      def integration_session
466
        @integration_session ||= create_session(app)
467 468
      end

469 470 471
      # Reset the current session. This is useful for testing multiple sessions
      # in a single test case.
      def reset!
472
        @integration_session = create_session(app)
473 474 475 476 477 478 479 480 481 482 483 484
      end

      def create_session(app)
        klass = APP_SESSIONS[app] ||= Class.new(Integration::Session) {
          # If the app is a Rails app, make url_helpers available on the session
          # This makes app.url_for and app.foo_path available in the console
          if app.respond_to?(:routes)
            include app.routes.url_helpers
            include app.routes.mounted_helpers
          end
        }
        klass.new(app)
485 486
      end

487 488 489 490
      def remove! # :nodoc:
        @integration_session = nil
      end

491
      %w(get post patch put head delete cookies assigns
492
         xml_http_request xhr get_via_redirect post_via_redirect).each do |method|
493
        define_method(method) do |*args|
494 495 496 497 498
          # reset the html_document variable, except for cookies/assigns calls
          unless method == 'cookies' || method == 'assigns'
            @html_document = nil
          end

499
          integration_session.__send__(method, *args).tap do
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
            copy_session_variables!
          end
        end
      end

      # Open a new session instance. If a block is given, the new session is
      # yielded to the block before being returned.
      #
      #   session = open_session do |sess|
      #     sess.extend(CustomAssertions)
      #   end
      #
      # By default, a single session is automatically created for you, but you
      # can use this method to open multiple sessions that ought to be tested
      # simultaneously.
G
Guo Xiang Tan 已提交
515
      def open_session
516 517
        dup.tap do |session|
          yield session if block_given?
518 519 520 521 522 523
        end
      end

      # Copy the instance variables from the current session instance into the
      # test instance.
      def copy_session_variables! #:nodoc:
A
Aaron Patterson 已提交
524 525 526
        @controller = @integration_session.controller
        @response   = @integration_session.response
        @request    = @integration_session.request
527 528
      end

529 530 531
      def default_url_options
        integration_session.default_url_options
      end
532

533 534
      def default_url_options=(options)
        integration_session.default_url_options = options
535 536
      end

537
      def respond_to?(method, include_private = false)
538
        integration_session.respond_to?(method, include_private) || super
539 540
      end

541 542
      # Delegate unhandled messages to the current session instance.
      def method_missing(sym, *args, &block)
543 544
        if integration_session.respond_to?(sym)
          integration_session.__send__(sym, *args, &block).tap do
545 546 547 548
            copy_session_variables!
          end
        else
          super
549 550 551
        end
      end
    end
552 553
  end

554
  # An integration test spans multiple controllers and actions,
555 556 557 558
  # tying them all together to ensure they work together as expected. It tests
  # more completely than either unit or functional tests do, exercising the
  # entire stack, from the dispatcher to the database.
  #
559
  # At its simplest, you simply extend <tt>IntegrationTest</tt> and write your tests
560 561
  # using the get/post methods:
  #
562
  #   require "test_helper"
563
  #
564
  #   class ExampleTest < ActionDispatch::IntegrationTest
565 566 567 568 569 570 571 572
  #     fixtures :people
  #
  #     def test_login
  #       # get the login page
  #       get "/login"
  #       assert_equal 200, status
  #
  #       # post the login and follow through to the home page
573 574
  #       post "/login", params: { username: people(:jamis).username,
  #         password: people(:jamis).password }
575 576 577 578 579 580 581 582 583
  #       follow_redirect!
  #       assert_equal 200, status
  #       assert_equal "/home", path
  #     end
  #   end
  #
  # However, you can also have multiple session instances open per test, and
  # even extend those instances with assertions and methods to create a very
  # powerful testing DSL that is specific for your application. You can even
584
  # reference any named routes you happen to have defined.
585
  #
586
  #   require "test_helper"
587
  #
588
  #   class AdvancedTest < ActionDispatch::IntegrationTest
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
  #     fixtures :people, :rooms
  #
  #     def test_login_and_speak
  #       jamis, david = login(:jamis), login(:david)
  #       room = rooms(:office)
  #
  #       jamis.enter(room)
  #       jamis.speak(room, "anybody home?")
  #
  #       david.enter(room)
  #       david.speak(room, "hello!")
  #     end
  #
  #     private
  #
  #       module CustomAssertions
  #         def enter(room)
  #           # reference a named route, for maximum internal consistency!
A
AvnerCohen 已提交
607
  #           get(room_url(id: room.id))
608 609 610 611 612
  #           assert(...)
  #           ...
  #         end
  #
  #         def speak(room, message)
613
  #           post "/say/#{room.id}", xhr: true, params: { message: message }
614 615 616 617 618 619 620 621 622
  #           assert(...)
  #           ...
  #         end
  #       end
  #
  #       def login(who)
  #         open_session do |sess|
  #           sess.extend(CustomAssertions)
  #           who = people(who)
623 624
  #           sess.post "/login", params: { username: who.username,
  #             password: who.password }
625 626 627 628
  #           assert(...)
  #         end
  #       end
  #   end
629 630 631 632 633 634 635 636 637 638 639 640 641 642
  #
  # Another longer example would be:
  #
  # A simple integration test that exercises multiple controllers:
  #
  #   require 'test_helper'
  #
  #   class UserFlowsTest < ActionDispatch::IntegrationTest
  #     test "login and browse site" do
  #       # login via https
  #       https!
  #       get "/login"
  #       assert_response :success
  #
643 644
  #       post "/login", params: { username: users(:david).username, password: users(:david).password }
  #       follow_redirect!
645 646 647 648 649 650
  #       assert_equal '/welcome', path
  #       assert_equal 'Welcome david!', flash[:notice]
  #
  #       https!(false)
  #       get "/articles/all"
  #       assert_response :success
651
  #       assert_select 'h1', 'Articles'
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
  #     end
  #   end
  #
  # As you can see the integration test involves multiple controllers and
  # exercises the entire stack from database to dispatcher. In addition you can
  # have multiple session instances open simultaneously in a test and extend
  # those instances with assertion methods to create a very powerful testing
  # DSL (domain-specific language) just for your application.
  #
  # Here's an example of multiple sessions and custom DSL in an integration test
  #
  #   require 'test_helper'
  #
  #   class UserFlowsTest < ActionDispatch::IntegrationTest
  #     test "login and browse site" do
  #       # User david logs in
  #       david = login(:david)
  #       # User guest logs in
  #       guest = login(:guest)
  #
  #       # Both are now available in different sessions
  #       assert_equal 'Welcome david!', david.flash[:notice]
  #       assert_equal 'Welcome guest!', guest.flash[:notice]
  #
  #       # User david can browse site
  #       david.browses_site
  #       # User guest can browse site as well
  #       guest.browses_site
  #
  #       # Continue with other assertions
  #     end
  #
  #     private
  #
  #       module CustomDsl
  #         def browses_site
  #           get "/products/all"
  #           assert_response :success
690
  #           assert_select 'h1', 'Products'
691 692 693 694 695 696 697 698
  #         end
  #       end
  #
  #       def login(user)
  #         open_session do |sess|
  #           sess.extend(CustomDsl)
  #           u = users(user)
  #           sess.https!
699
  #           sess.post "/login", params: { username: u.username, password: u.password }
700 701 702 703 704 705
  #           assert_equal '/welcome', sess.path
  #           sess.https!(false)
  #         end
  #       end
  #   end
  #
706 707 708 709 710 711
  # You can also test your JSON API easily by setting what the request should
  # be encoded as:
  #
  #   require 'test_helper'
  #
  #   class ApiTest < ActionDispatch::IntegrationTest
712
  #     test 'creates articles' do
713 714 715 716 717
  #       assert_difference -> { Article.count } do
  #         post articles_path, params: { article: { title: 'Ahoy!' } }, as: :json
  #       end
  #
  #       assert_response :success
718
  #       assert_equal({ id: Arcticle.last.id, title: 'Ahoy!' }, response.parsed_body)
719 720 721 722 723 724
  #     end
  #   end
  #
  # The `as` option sets the format to JSON, sets the content type to
  # 'application/json' and encodes the parameters as JSON.
  #
725 726 727 728
  # Calling `parsed_body` on the response parses the response body as what
  # the last request was encoded as. If the request wasn't encoded `as` something,
  # it's the same as calling `body`.
  #
729 730
  # For any custom MIME Types you've registered, you can even add your own encoders with:
  #
731 732 733 734 735
  #   ActionDispatch::IntegrationTest.register_encoder :wibble,
  #     param_encoder: -> params { params.to_wibble },
  #     response_parser: -> body { body }
  #
  # Where `param_encoder` defines how the params should be encoded and
736 737
  # `response_parser` defines how the response body should be parsed through
  # `parsed_body`.
738
  #
739 740
  # Consult the Rails Testing Guide for more.

741
  class IntegrationTest < ActiveSupport::TestCase
742 743 744 745 746 747
    module UrlOptions
      extend ActiveSupport::Concern
      def url_options
        integration_session.url_options
      end
    end
748

749 750
    module Behavior
      extend ActiveSupport::Concern
751

752 753
      include Integration::Runner
      include ActionController::TemplateAssertions
754

755 756 757 758 759 760
      included do
        include ActionDispatch::Routing::UrlFor
        include UrlOptions # don't let UrlFor override the url_options method
        ActiveSupport.run_load_hooks(:action_dispatch_integration_test, self)
        @@app = nil
      end
761

762 763 764 765
      module ClassMethods
        def app
          defined?(@@app) ? @@app : ActionDispatch.test_app
        end
766

767 768 769
        def app=(app)
          @@app = app
        end
770

771 772 773 774 775 776 777 778
        def register_encoder(*args)
          Integration::Session::RequestEncoder.register_encoder(*args)
        end
      end

      def app
        super || self.class.app
      end
779

780 781 782
      def document_root_element
        html_document.root
      end
783
    end
784

785
    include Behavior
786
  end
787
end