integration.rb 21.2 KB
Newer Older
1 2 3 4 5 6 7
require "stringio"
require "uri"
require "active_support/core_ext/kernel/singleton_class"
require "active_support/core_ext/object/try"
require "active_support/core_ext/string/strip"
require "rack/test"
require "minitest"
8

9
require "action_dispatch/testing/request_encoder"
10

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

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

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

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

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

69
      # Performs a HEAD request with the given parameters. See +#get+ for more
70
      # details.
71 72
      def head(path, *args)
        process_with_kwargs(:head, path, *args)
73 74 75 76 77 78 79 80 81 82 83 84
      end

      # 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
    end

85 86
    # An instance of this class represents a set of requests and responses
    # performed sequentially by a test process. Because you can instantiate
87 88 89
    # multiple sessions and run them side-by-side, you can also mimic (to some
    # limited extent) multiple simultaneous users interacting with your system.
    #
90 91 92
    # Typically, you will instantiate a new session using
    # IntegrationTest#open_session, rather than instantiating
    # Integration::Session directly.
93
    class Session
94 95
      DEFAULT_HOST = "www.example.com"

96
      include Minitest::Assertions
97
      include RequestHelpers, Assertions
98

99
      %w( status status_message headers body redirect? ).each do |method|
100
        delegate method, to: :response, allow_nil: true
101
      end
102

103
      %w( path ).each do |method|
104
        delegate method, to: :request, allow_nil: true
105
      end
106 107

      # The hostname used in the last request.
108 109 110 111
      def host
        @host || DEFAULT_HOST
      end
      attr_writer :host
112 113 114

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

116 117 118
      # The Accept header to send.
      attr_accessor :accept

119 120
      # A map of the cookies returned by the last response, and which will be
      # sent with the next request.
121
      def cookies
122
        _mock_session.cookie_jar
123
      end
124 125 126 127 128 129 130 131 132 133

      # 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

134 135 136
      # A running counter of the number of requests processed.
      attr_accessor :request_count

137 138
      include ActionDispatch::Routing::UrlFor

P
Pratik Naik 已提交
139
      # Create and initialize a new Session instance.
140
      def initialize(app)
J
José Valim 已提交
141
        super()
142
        @app = app
143

144 145 146
        reset!
      end

147 148 149 150
      def url_options
        @url_options ||= default_url_options.dup.tap do |url_options|
          url_options.reverse_merge!(controller.url_options) if controller

151
          if @app.respond_to?(:routes)
152 153 154
            url_options.reverse_merge!(@app.routes.default_url_options)
          end

155
          url_options.reverse_merge!(host: host, protocol: https? ? "https" : "http")
156
        end
157 158
      end

159 160 161 162 163 164 165 166
      # 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
167
        @_mock_session = nil
168
        @request_count = 0
169
        @url_options = nil
170

171
        self.host        = DEFAULT_HOST
172
        self.remote_addr = "127.0.0.1"
173 174 175
        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 已提交
176

177
        unless defined? @named_routes_configured
J
Jamis Buck 已提交
178 179 180 181
          # the helpers are made protected by default--we make them public for
          # easier access during testing and troubleshooting.
          @named_routes_configured = true
        end
182 183 184 185 186 187
      end

      # Specify whether or not the session should mimic a secure HTTPS request.
      #
      #   session.https!
      #   session.https!(false)
188
      def https!(flag = true)
189
        @https = flag
190 191
      end

192
      # Returns +true+ if the session is mimicking a secure HTTPS request.
193 194 195 196 197 198 199 200 201 202
      #
      #   if session.https?
      #     ...
      #   end
      def https?
        @https
      end

      # Set the host name to use in the next request.
      #
203
      #   session.host! "www.example.com"
A
Aaron Patterson 已提交
204
      alias :host! :host=
205 206

      private
207 208 209
        def _mock_session
          @_mock_session ||= Rack::MockSession.new(@app, host)
        end
210

211
        def process_with_kwargs(http_method, path, *args)
212
          if kwarg_request?(args)
213 214
            process(http_method, path, *args)
          else
215
            non_kwarg_request_warning if args.any?
216
            process(http_method, path, params: args[0], headers: args[1])
217 218 219
          end
        end

220
        REQUEST_KWARGS = %i(params headers env xhr as)
221
        def kwarg_request?(args)
222 223 224 225 226
          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)
227
            ActionDispatch::IntegrationTest HTTP request methods will accept only
G
Guo Xiang Tan 已提交
228 229
            the following keyword arguments in future Rails versions:
            #{REQUEST_KWARGS.join(', ')}
230 231 232 233 234 235

            Examples:

            get '/profile',
              params: { id: 1 },
              headers: { 'X-Extra-Header' => '123' },
A
Arthur Neves 已提交
236
              env: { 'action_dispatch.custom' => 'custom' },
237 238
              xhr: true,
              as: :json
239 240 241
          MSG
        end

242
        # Performs the actual request.
243 244
        def process(method, path, params: nil, headers: nil, env: nil, xhr: false, as: nil)
          request_encoder = RequestEncoder.encoder(as)
245 246 247
          headers ||= {}

          if method == :get && as == :json && params
248
            headers["X-Http-Method-Override"] = "GET"
249 250
            method = :post
          end
251

252
          if path =~ %r{://}
253 254 255 256 257 258 259 260
            path = build_expanded_path(path, request_encoder) do |location|
              https! URI::HTTPS === location if location.scheme

              if url_host = location.host
                default = Rack::Request::DEFAULT_PORTS[location.scheme]
                url_host += ":#{location.port}" if default != location.port
                host! url_host
              end
261
            end
K
Kasper Timm Hansen 已提交
262
          elsif as
263
            path = build_expanded_path(path, request_encoder)
264
          end
265

266
          hostname, port = host.split(":")
267

268
          request_env = {
269
            :method => method,
270
            :params => request_encoder.encode_params(params),
271

272
            "SERVER_NAME"     => hostname,
273
            "SERVER_PORT"     => port || (https? ? "443" : "80"),
274 275 276
            "HTTPS"           => https? ? "on" : "off",
            "rack.url_scheme" => https? ? "https" : "http",

277
            "REQUEST_URI"    => path,
278
            "HTTP_HOST"      => host,
279
            "REMOTE_ADDR"    => remote_addr,
280
            "CONTENT_TYPE"   => request_encoder.content_type,
281
            "HTTP_ACCEPT"    => accept
282
          }
283

284 285 286
          wrapped_headers = Http::Headers.from_hash({})
          wrapped_headers.merge!(headers) if headers

287
          if xhr
288 289
            wrapped_headers["HTTP_X_REQUESTED_WITH"] = "XMLHttpRequest"
            wrapped_headers["HTTP_ACCEPT"] ||= [Mime[:js], Mime[:html], Mime[:xml], "text/xml", "*/*"].join(", ")
290 291
          end

292
          # this modifies the passed request_env directly
293 294
          if wrapped_headers.present?
            Http::Headers.from_hash(request_env).merge!(wrapped_headers)
295 296
          end
          if env.present?
297
            Http::Headers.from_hash(request_env).merge!(env)
298
          end
299

300
          session = Rack::Test::Session.new(_mock_session)
301

302 303
          # NOTE: rack-test v0.5 doesn't build a default uri correctly
          # Make sure requested path is always a full uri
304
          session.request(build_full_uri(path, request_env), request_env)
305

306
          @request_count += 1
307
          @request  = ActionDispatch::Request.new(session.last_request.env)
308
          response = _mock_session.last_response
309
          @response = ActionDispatch::TestResponse.from_response(response)
E
eileencodes 已提交
310
          @response.request = @request
311
          @html_document = nil
312
          @url_options = nil
313

314
          @controller = @request.controller_instance
315

316
          response.status
317
        end
318 319 320 321

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

323 324 325 326 327 328
        def build_expanded_path(path, request_encoder)
          location = URI.parse(path)
          yield location if block_given?
          path = request_encoder.append_format_to location.path
          location.query ? "#{path}?#{location.query}" : path
        end
329 330
    end

331
    module Runner
332 333
      include ActionDispatch::Assertions

334 335
      APP_SESSIONS = {}

336 337
      attr_reader :app

338 339 340 341 342
      def initialize(*args, &blk)
        super(*args, &blk)
        @integration_session = nil
      end

343
      def before_setup # :nodoc:
344
        @app = nil
E
eileencodes 已提交
345
        super
346 347 348
      end

      def integration_session
349
        @integration_session ||= create_session(app)
350 351
      end

352 353 354
      # Reset the current session. This is useful for testing multiple sessions
      # in a single test case.
      def reset!
355
        @integration_session = create_session(app)
356 357 358 359 360 361 362 363 364 365 366 367
      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)
368 369
      end

370 371 372 373
      def remove! # :nodoc:
        @integration_session = nil
      end

374
      %w(get post patch put head delete cookies assigns
375
         xml_http_request xhr get_via_redirect post_via_redirect).each do |method|
376
        define_method(method) do |*args|
377
          # reset the html_document variable, except for cookies/assigns calls
378
          unless method == "cookies" || method == "assigns"
379 380 381
            @html_document = nil
          end

382
          integration_session.__send__(method, *args).tap do
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
            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 已提交
398
      def open_session
399 400
        dup.tap do |session|
          yield session if block_given?
401 402 403 404 405 406
        end
      end

      # Copy the instance variables from the current session instance into the
      # test instance.
      def copy_session_variables! #:nodoc:
A
Aaron Patterson 已提交
407 408 409
        @controller = @integration_session.controller
        @response   = @integration_session.response
        @request    = @integration_session.request
410 411
      end

412 413 414
      def default_url_options
        integration_session.default_url_options
      end
415

416 417
      def default_url_options=(options)
        integration_session.default_url_options = options
418 419
      end

420
      def respond_to_missing?(method, include_private = false)
421
        integration_session.respond_to?(method, include_private) || super
422 423
      end

424 425
      # Delegate unhandled messages to the current session instance.
      def method_missing(sym, *args, &block)
426 427
        if integration_session.respond_to?(sym)
          integration_session.__send__(sym, *args, &block).tap do
428 429 430 431
            copy_session_variables!
          end
        else
          super
432 433 434
        end
      end
    end
435 436
  end

437
  # An integration test spans multiple controllers and actions,
438 439 440 441
  # 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.
  #
442
  # At its simplest, you simply extend <tt>IntegrationTest</tt> and write your tests
443 444
  # using the get/post methods:
  #
445
  #   require "test_helper"
446
  #
447
  #   class ExampleTest < ActionDispatch::IntegrationTest
448 449 450 451 452 453 454 455
  #     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
456 457
  #       post "/login", params: { username: people(:jamis).username,
  #         password: people(:jamis).password }
458 459 460 461 462 463 464 465 466
  #       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
467
  # reference any named routes you happen to have defined.
468
  #
469
  #   require "test_helper"
470
  #
471
  #   class AdvancedTest < ActionDispatch::IntegrationTest
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
  #     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 已提交
490
  #           get(room_url(id: room.id))
491 492 493 494 495
  #           assert(...)
  #           ...
  #         end
  #
  #         def speak(room, message)
496
  #           post "/say/#{room.id}", xhr: true, params: { message: message }
497 498 499 500 501 502 503 504 505
  #           assert(...)
  #           ...
  #         end
  #       end
  #
  #       def login(who)
  #         open_session do |sess|
  #           sess.extend(CustomAssertions)
  #           who = people(who)
506 507
  #           sess.post "/login", params: { username: who.username,
  #             password: who.password }
508 509 510 511
  #           assert(...)
  #         end
  #       end
  #   end
512 513 514 515 516 517 518 519 520 521 522 523 524 525
  #
  # 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
  #
526 527
  #       post "/login", params: { username: users(:david).username, password: users(:david).password }
  #       follow_redirect!
528 529 530 531 532 533
  #       assert_equal '/welcome', path
  #       assert_equal 'Welcome david!', flash[:notice]
  #
  #       https!(false)
  #       get "/articles/all"
  #       assert_response :success
534
  #       assert_select 'h1', 'Articles'
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
  #     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
573
  #           assert_select 'h1', 'Products'
574 575 576 577 578 579 580 581
  #         end
  #       end
  #
  #       def login(user)
  #         open_session do |sess|
  #           sess.extend(CustomDsl)
  #           u = users(user)
  #           sess.https!
582
  #           sess.post "/login", params: { username: u.username, password: u.password }
583 584 585 586 587 588
  #           assert_equal '/welcome', sess.path
  #           sess.https!(false)
  #         end
  #       end
  #   end
  #
589 590 591
  # See the {request helpers documentation}[rdoc-ref:ActionDispatch::Integration::RequestHelpers] for help on how to
  # use +get+, etc.
  #
592 593
  # === Changing the request encoding
  #
594 595 596
  # You can also test your JSON API easily by setting what the request should
  # be encoded as:
  #
597
  #   require "test_helper"
598 599
  #
  #   class ApiTest < ActionDispatch::IntegrationTest
600
  #     test "creates articles" do
601
  #       assert_difference -> { Article.count } do
602
  #         post articles_path, params: { article: { title: "Ahoy!" } }, as: :json
603 604 605
  #       end
  #
  #       assert_response :success
606
  #       assert_equal({ id: Arcticle.last.id, title: "Ahoy!" }, response.parsed_body)
607 608 609
  #     end
  #   end
  #
610 611
  # The +as+ option sets the format to JSON, sets the content type to
  # "application/json" and encodes the parameters as JSON.
612
  #
613 614
  # Calling +parsed_body+ on the response parses the response body based on the
  # last response MIME type.
615
  #
616
  # For any custom MIME types you've registered, you can even add your own encoders with:
617
  #
618 619 620 621
  #   ActionDispatch::IntegrationTest.register_encoder :wibble,
  #     param_encoder: -> params { params.to_wibble },
  #     response_parser: -> body { body }
  #
622 623 624
  # Where +param_encoder+ defines how the params should be encoded and
  # +response_parser+ defines how the response body should be parsed through
  # +parsed_body+.
625
  #
626 627
  # Consult the Rails Testing Guide for more.

628
  class IntegrationTest < ActiveSupport::TestCase
629 630
    include TestProcess

631 632
    undef :assigns

633 634 635 636 637 638
    module UrlOptions
      extend ActiveSupport::Concern
      def url_options
        integration_session.url_options
      end
    end
639

640 641
    module Behavior
      extend ActiveSupport::Concern
642

643 644
      include Integration::Runner
      include ActionController::TemplateAssertions
645

646 647 648 649 650 651
      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
652

653 654
      module ClassMethods
        def app
655 656 657 658 659
          if defined?(@@app) && @@app
            @@app
          else
            ActionDispatch.test_app
          end
660
        end
661

662 663 664
        def app=(app)
          @@app = app
        end
665

666
        def register_encoder(*args)
667
          RequestEncoder.register_encoder(*args)
668 669 670 671 672 673
        end
      end

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

675 676 677
      def document_root_element
        html_document.root
      end
678
    end
679

680
    include Behavior
681
  end
682
end