integration.rb 22.1 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'
J
Joshua Peek 已提交
5
require 'rack/test'
6
require 'minitest'
7 8

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

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

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

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

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

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

      # Performs an XMLHttpRequest request with the given parameters, mirroring
      # a request from the Prototype library.
      #
75 76
      # The request_method is +:get+, +:post+, +:patch+, +:put+, +:delete+ or
      # +:head+; the parameters are +nil+, a hash, or a url-encoded or multipart
77
      # string; the headers are a hash.
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
      #
      # Example:
      #
      #   xhr :get, '/feed', params: { since: 201501011400 }
      def xml_http_request(request_method, path, *args)
        if kwarg_request?(*args)
          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

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

        process(request_method, path, params: params, headers: headers, xhr: true)
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
      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.
117 118 119 120 121
      #
      # Example:
      #
      #   request_via_redirect :post, '/welcome',
      #     params: { ref_id: 14 },
122
      #     headers: { "X-Test-Header" => "testvalue" }
123 124 125
      def request_via_redirect(http_method, path, *args)
        process_with_kwargs(http_method, path, *args)

126 127 128 129 130 131
        follow_redirect! while redirect?
        status
      end

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

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

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

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

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

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

177
      include Minitest::Assertions
J
Joshua Peek 已提交
178
      include TestProcess, RequestHelpers, Assertions
179

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

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

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

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

197 198 199
      # The Accept header to send.
      attr_accessor :accept

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

      # 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

215 216 217
      # A running counter of the number of requests processed.
      attr_accessor :request_count

218 219
      include ActionDispatch::Routing::UrlFor

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

        # 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
227 228
        if app.respond_to?(:routes)
          singleton_class.class_eval do
229
            include app.routes.url_helpers
230
            include app.routes.mounted_helpers
231
          end
232 233
        end

234 235 236
        reset!
      end

237 238 239 240
      def url_options
        @url_options ||= default_url_options.dup.tap do |url_options|
          url_options.reverse_merge!(controller.url_options) if controller

241
          if @app.respond_to?(:routes)
242 243 244 245 246
            url_options.reverse_merge!(@app.routes.default_url_options)
          end

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

249 250 251 252 253 254 255 256
      # 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
257
        @_mock_session = nil
258
        @request_count = 0
259
        @url_options = nil
260

261
        self.host        = DEFAULT_HOST
262
        self.remote_addr = "127.0.0.1"
263 264 265
        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 已提交
266

267
        unless defined? @named_routes_configured
J
Jamis Buck 已提交
268 269 270 271
          # the helpers are made protected by default--we make them public for
          # easier access during testing and troubleshooting.
          @named_routes_configured = true
        end
272 273 274 275 276 277
      end

      # Specify whether or not the session should mimic a secure HTTPS request.
      #
      #   session.https!
      #   session.https!(false)
278
      def https!(flag = true)
279
        @https = flag
280 281
      end

282
      # Returns +true+ if the session is mimicking a secure HTTPS request.
283 284 285 286 287 288 289 290 291 292
      #
      #   if session.https?
      #     ...
      #   end
      def https?
        @https
      end

      # Set the host name to use in the next request.
      #
293
      #   session.host! "www.example.com"
A
Aaron Patterson 已提交
294
      alias :host! :host=
295 296

      private
297 298 299
        def _mock_session
          @_mock_session ||= Rack::MockSession.new(@app, host)
        end
300

301 302 303 304 305 306 307 308 309
        def process_with_kwargs(http_method, path, *args)
          if kwarg_request?(*args)
            process(http_method, path, *args)
          else
            non_kwarg_request_warning if args.present?
            process(http_method, path, { params: args[0], headers: args[1] })
          end
        end

310
        REQUEST_KWARGS = %i(params headers env xhr)
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
        def kwarg_request?(*args)
          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)
            ActionDispatch::Integration::TestCase HTTP request methods will accept only
            keyword arguments in future Rails versions.

            Examples:

            get '/profile',
              params: { id: 1 },
              headers: { 'X-Extra-Header' => '123' },
              env: { 'action_dispatch.custom' => 'custom' }

            xhr :post, '/profile',
              params: { id: 1 }
          MSG
        end

332
        # Performs the actual request.
333
        def process(method, path, params: nil, headers: nil, env: nil, xhr: false)
334 335 336
          if path =~ %r{://}
            location = URI.parse(path)
            https! URI::HTTPS === location if location.scheme
337
            host! "#{location.host}:#{location.port}" if location.host
338 339
            path = location.query ? "#{location.path}?#{location.query}" : location.path
          end
340

341
          hostname, port = host.split(':')
342

343
          request_env = {
344
            :method => method,
345
            :params => params,
346

347
            "SERVER_NAME"     => hostname,
348
            "SERVER_PORT"     => port || (https? ? "443" : "80"),
349 350 351
            "HTTPS"           => https? ? "on" : "off",
            "rack.url_scheme" => https? ? "https" : "http",

352
            "REQUEST_URI"    => path,
353
            "HTTP_HOST"      => host,
354
            "REMOTE_ADDR"    => remote_addr,
355
            "CONTENT_TYPE"   => "application/x-www-form-urlencoded",
356
            "HTTP_ACCEPT"    => accept
357
          }
358 359 360 361 362 363 364

          if xhr
            headers ||= {}
            headers['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
            headers['HTTP_ACCEPT'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
          end

365 366 367 368 369 370 371
          # this modifies the passed request_env directly
          if headers.present?
            Http::Headers.new(request_env).merge!(headers)
          end
          if env.present?
            Http::Headers.new(request_env).merge!(env)
          end
372

373
          session = Rack::Test::Session.new(_mock_session)
374

375 376
          # NOTE: rack-test v0.5 doesn't build a default uri correctly
          # Make sure requested path is always a full uri
377
          session.request(build_full_uri(path, request_env), request_env)
378

379
          @request_count += 1
380
          @request  = ActionDispatch::Request.new(session.last_request.env)
381
          response = _mock_session.last_response
382
          @response = ActionDispatch::TestResponse.new(response.status, response.headers, response.body)
383
          @html_document = nil
384
          @url_options = nil
385

386 387
          @controller = session.last_request.env['action_controller.instance']

388
          response.status
389
        end
390 391 392 393

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

396
    module Runner
397 398
      include ActionDispatch::Assertions

399
      def app
400
        @app ||= nil
401 402
      end

403 404 405
      # Reset the current session. This is useful for testing multiple sessions
      # in a single test case.
      def reset!
406
        @integration_session = Integration::Session.new(app)
407 408
      end

409 410 411 412
      def remove! # :nodoc:
        @integration_session = nil
      end

413
      %w(get post patch put head delete cookies assigns
414
         xml_http_request xhr get_via_redirect post_via_redirect).each do |method|
415
        define_method(method) do |*args|
416
          reset! unless integration_session
417 418 419 420 421 422 423

          # reset the html_document variable, except for cookies/assigns calls
          unless method == 'cookies' || method == 'assigns'
            @html_document = nil
            reset_template_assertion
          end

424
          integration_session.__send__(method, *args).tap do
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
            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 已提交
440
      def open_session
441 442
        dup.tap do |session|
          yield session if block_given?
443 444 445 446 447 448
        end
      end

      # Copy the instance variables from the current session instance into the
      # test instance.
      def copy_session_variables! #:nodoc:
449
        return unless integration_session
450
        %w(controller response request).each do |var|
451
          instance_variable_set("@#{var}", @integration_session.__send__(var))
452 453 454
        end
      end

455 456 457 458
      def default_url_options
        reset! unless integration_session
        integration_session.default_url_options
      end
459

460
      def default_url_options=(options)
461
        reset! unless integration_session
462
        integration_session.default_url_options = options
463 464
      end

465
      def respond_to?(method, include_private = false)
466
        integration_session.respond_to?(method, include_private) || super
467 468
      end

469 470
      # Delegate unhandled messages to the current session instance.
      def method_missing(sym, *args, &block)
471 472 473
        reset! unless integration_session
        if integration_session.respond_to?(sym)
          integration_session.__send__(sym, *args, &block).tap do
474 475 476 477
            copy_session_variables!
          end
        else
          super
478 479
        end
      end
480 481 482 483 484

      private
        def integration_session
          @integration_session ||= nil
        end
485
    end
486 487
  end

488
  # An integration test spans multiple controllers and actions,
489 490 491 492
  # 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.
  #
493
  # At its simplest, you simply extend <tt>IntegrationTest</tt> and write your tests
494 495
  # using the get/post methods:
  #
496
  #   require "test_helper"
497
  #
498
  #   class ExampleTest < ActionDispatch::IntegrationTest
499 500 501 502 503 504 505 506
  #     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
A
AvnerCohen 已提交
507 508
  #       post "/login", username: people(:jamis).username,
  #         password: people(:jamis).password
509 510 511 512 513 514 515 516 517
  #       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
518
  # reference any named routes you happen to have defined.
519
  #
520
  #   require "test_helper"
521
  #
522
  #   class AdvancedTest < ActionDispatch::IntegrationTest
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
  #     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 已提交
541
  #           get(room_url(id: room.id))
542 543 544 545 546
  #           assert(...)
  #           ...
  #         end
  #
  #         def speak(room, message)
A
AvnerCohen 已提交
547
  #           xml_http_request "/say/#{room.id}", message: message
548 549 550 551 552 553 554 555 556
  #           assert(...)
  #           ...
  #         end
  #       end
  #
  #       def login(who)
  #         open_session do |sess|
  #           sess.extend(CustomAssertions)
  #           who = people(who)
A
AvnerCohen 已提交
557 558
  #           sess.post "/login", username: who.username,
  #             password: who.password
559 560 561 562
  #           assert(...)
  #         end
  #       end
  #   end
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
  #
  # 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
  #
  #       post_via_redirect "/login", username: users(:david).username, password: users(:david).password
  #       assert_equal '/welcome', path
  #       assert_equal 'Welcome david!', flash[:notice]
  #
  #       https!(false)
  #       get "/articles/all"
  #       assert_response :success
  #       assert assigns(:articles)
  #     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
  #           assert assigns(:products)
  #         end
  #       end
  #
  #       def login(user)
  #         open_session do |sess|
  #           sess.extend(CustomDsl)
  #           u = users(user)
  #           sess.https!
  #           sess.post "/login", username: u.username, password: u.password
  #           assert_equal '/welcome', sess.path
  #           sess.https!(false)
  #         end
  #       end
  #   end
  #
  # Consult the Rails Testing Guide for more.

641
  class IntegrationTest < ActiveSupport::TestCase
642
    include Integration::Runner
643
    include ActionController::TemplateAssertions
644
    include ActionDispatch::Routing::UrlFor
645 646 647 648

    @@app = nil

    def self.app
649
      @@app || ActionDispatch.test_app
650 651 652 653 654 655 656 657 658
    end

    def self.app=(app)
      @@app = app
    end

    def app
      super || self.class.app
    end
659 660 661 662 663

    def url_options
      reset! unless integration_session
      integration_session.url_options
    end
664 665

    def document_root_element
666
      html_document.root
667
    end
668
  end
669
end