integration.rb 17.4 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 7

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

34
      # Performs a POST request with the given parameters. See +#get+ for more
35 36 37 38 39
      # details.
      def post(path, parameters = nil, headers = nil)
        process :post, path, parameters, headers
      end

40 41 42 43 44 45
      # Performs a PATCH request with the given parameters. See +#get+ for more
      # details.
      def patch(path, parameters = nil, headers = nil)
        process :patch, path, parameters, headers
      end

46
      # Performs a PUT request with the given parameters. See +#get+ for more
47 48 49 50 51
      # details.
      def put(path, parameters = nil, headers = nil)
        process :put, path, parameters, headers
      end

52
      # Performs a DELETE request with the given parameters. See +#get+ for
53 54 55 56 57
      # more details.
      def delete(path, parameters = nil, headers = nil)
        process :delete, path, parameters, headers
      end

58
      # Performs a HEAD request with the given parameters. See +#get+ for more
59 60 61 62 63
      # details.
      def head(path, parameters = nil, headers = nil)
        process :head, path, parameters, headers
      end

64 65 66 67 68 69
      # Performs a OPTIONS request with the given parameters. See +#get+ for
      # more details.
      def options(path, parameters = nil, headers = nil)
        process :options, path, parameters, headers
      end

70 71 72
      # Performs an XMLHttpRequest request with the given parameters, mirroring
      # a request from the Prototype library.
      #
73 74
      # The request_method is +:get+, +:post+, +:patch+, +:put+, +:delete+ or
      # +:head+; the parameters are +nil+, a hash, or a url-encoded or multipart
75
      # string; the headers are a hash.
76 77
      def xml_http_request(request_method, path, parameters = nil, headers = nil)
        headers ||= {}
78 79
        headers['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
        headers['HTTP_ACCEPT'] ||= [Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
        process(request_method, path, parameters, headers)
      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.
      def request_via_redirect(http_method, path, parameters = nil, headers = nil)
        process(http_method, path, parameters, headers)
        follow_redirect! while redirect?
        status
      end

      # Performs a GET request, following any subsequent redirect.
      # See +request_via_redirect+ for more information.
      def get_via_redirect(path, parameters = nil, headers = nil)
        request_via_redirect(:get, path, parameters, headers)
      end

      # Performs a POST request, following any subsequent redirect.
      # See +request_via_redirect+ for more information.
      def post_via_redirect(path, parameters = nil, headers = nil)
        request_via_redirect(:post, path, parameters, headers)
      end

115 116 117 118 119 120
      # Performs a PATCH request, following any subsequent redirect.
      # See +request_via_redirect+ for more information.
      def patch_via_redirect(path, parameters = nil, headers = nil)
        request_via_redirect(:patch, path, parameters, headers)
      end

121 122 123 124 125 126 127 128 129 130 131 132 133
      # Performs a PUT request, following any subsequent redirect.
      # See +request_via_redirect+ for more information.
      def put_via_redirect(path, parameters = nil, headers = nil)
        request_via_redirect(:put, path, parameters, headers)
      end

      # Performs a DELETE request, following any subsequent redirect.
      # See +request_via_redirect+ for more information.
      def delete_via_redirect(path, parameters = nil, headers = nil)
        request_via_redirect(:delete, path, parameters, headers)
      end
    end

134 135
    # An instance of this class represents a set of requests and responses
    # performed sequentially by a test process. Because you can instantiate
136 137 138
    # multiple sessions and run them side-by-side, you can also mimic (to some
    # limited extent) multiple simultaneous users interacting with your system.
    #
139 140 141
    # Typically, you will instantiate a new session using
    # IntegrationTest#open_session, rather than instantiating
    # Integration::Session directly.
142
    class Session
143 144
      DEFAULT_HOST = "www.example.com"

145
      include MiniTest::Assertions
J
Joshua Peek 已提交
146
      include TestProcess, RequestHelpers, Assertions
147

148 149 150
      %w( status status_message headers body redirect? ).each do |method|
        delegate method, :to => :response, :allow_nil => true
      end
151

152 153 154
      %w( path ).each do |method|
        delegate method, :to => :request, :allow_nil => true
      end
155 156

      # The hostname used in the last request.
157 158 159 160
      def host
        @host || DEFAULT_HOST
      end
      attr_writer :host
161 162 163

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

165 166 167
      # The Accept header to send.
      attr_accessor :accept

168 169
      # A map of the cookies returned by the last response, and which will be
      # sent with the next request.
170
      def cookies
171
        _mock_session.cookie_jar
172
      end
173 174 175 176 177 178 179 180 181 182

      # 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

183 184 185
      # A running counter of the number of requests processed.
      attr_accessor :request_count

186 187
      include ActionDispatch::Routing::UrlFor

P
Pratik Naik 已提交
188
      # Create and initialize a new Session instance.
189
      def initialize(app)
J
José Valim 已提交
190
        super()
191
        @app = app
192 193 194

        # 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
195 196 197 198 199
        if app.respond_to?(:routes)
          singleton_class.class_eval do
            include app.routes.url_helpers if app.routes.respond_to?(:url_helpers)
            include app.routes.mounted_helpers if app.routes.respond_to?(:mounted_helpers)
          end
200 201
        end

202 203 204
        reset!
      end

205 206 207 208 209 210 211 212 213 214
      def url_options
        @url_options ||= default_url_options.dup.tap do |url_options|
          url_options.reverse_merge!(controller.url_options) if controller

          if @app.respond_to?(:routes) && @app.routes.respond_to?(:default_url_options)
            url_options.reverse_merge!(@app.routes.default_url_options)
          end

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

217 218 219 220 221 222 223 224
      # 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
225
        @_mock_session = nil
226
        @request_count = 0
227
        @url_options = nil
228

229
        self.host        = DEFAULT_HOST
230
        self.remote_addr = "127.0.0.1"
231 232 233
        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 已提交
234

235
        unless defined? @named_routes_configured
J
Jamis Buck 已提交
236 237 238 239
          # the helpers are made protected by default--we make them public for
          # easier access during testing and troubleshooting.
          @named_routes_configured = true
        end
240 241 242 243 244 245
      end

      # Specify whether or not the session should mimic a secure HTTPS request.
      #
      #   session.https!
      #   session.https!(false)
246
      def https!(flag = true)
247
        @https = flag
248 249
      end

P
Pratik Naik 已提交
250
      # Return +true+ if the session is mimicking a secure HTTPS request.
251 252 253 254 255 256 257 258 259 260
      #
      #   if session.https?
      #     ...
      #   end
      def https?
        @https
      end

      # Set the host name to use in the next request.
      #
261
      #   session.host! "www.example.com"
A
Aaron Patterson 已提交
262
      alias :host! :host=
263 264

      private
265 266 267
        def _mock_session
          @_mock_session ||= Rack::MockSession.new(@app, host)
        end
268

269
        # Performs the actual request.
270 271
        def process(method, path, parameters = nil, rack_env = nil)
          rack_env ||= {}
272 273 274 275 276 277
          if path =~ %r{://}
            location = URI.parse(path)
            https! URI::HTTPS === location if location.scheme
            host! location.host if location.host
            path = location.query ? "#{location.path}?#{location.query}" : location.path
          end
278

279 280 281
          unless ActionController::Base < ActionController::Testing
            ActionController::Base.class_eval do
              include ActionController::Testing
282
            end
283 284
          end

285
          hostname, port = host.split(':')
286

287
          env = {
288
            :method => method,
289
            :params => parameters,
290

291
            "SERVER_NAME"     => hostname,
292
            "SERVER_PORT"     => port || (https? ? "443" : "80"),
293 294 295
            "HTTPS"           => https? ? "on" : "off",
            "rack.url_scheme" => https? ? "https" : "http",

296
            "REQUEST_URI"    => path,
297
            "HTTP_HOST"      => host,
298
            "REMOTE_ADDR"    => remote_addr,
299
            "CONTENT_TYPE"   => "application/x-www-form-urlencoded",
300
            "HTTP_ACCEPT"    => accept
301
          }
302

303
          session = Rack::Test::Session.new(_mock_session)
304

305
          env.merge!(rack_env)
306

307 308 309 310 311 312 313 314 315
          # NOTE: rack-test v0.5 doesn't build a default uri correctly
          # Make sure requested path is always a full uri
          uri = URI.parse('/')
          uri.scheme ||= env['rack.url_scheme']
          uri.host   ||= env['SERVER_NAME']
          uri.port   ||= env['SERVER_PORT'].try(:to_i)
          uri += path

          session.request(uri.to_s, env)
316

317
          @request_count += 1
318
          @request  = ActionDispatch::Request.new(session.last_request.env)
319
          response = _mock_session.last_response
320
          @response = ActionDispatch::TestResponse.new(response.status, response.headers, response.body)
321
          @html_document = nil
322
          @url_options = nil
323

324 325
          @controller = session.last_request.env['action_controller.instance']

326
          return response.status
327 328 329
        end
    end

330
    module Runner
331 332
      include ActionDispatch::Assertions

333
      def app
334
        @app ||= nil
335 336
      end

337 338 339
      # Reset the current session. This is useful for testing multiple sessions
      # in a single test case.
      def reset!
340
        @integration_session = Integration::Session.new(app)
341 342
      end

343
      %w(get post patch put head delete options cookies assigns
344
         xml_http_request xhr get_via_redirect post_via_redirect).each do |method|
345
        define_method(method) do |*args|
346
          reset! unless integration_session
347
          # reset the html_document variable, but only for new get/post calls
348
          @html_document = nil unless method == 'cookies' || method == 'assigns'
349
          integration_session.__send__(method, *args).tap do
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
            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.
365
      def open_session(app = nil)
366 367
        dup.tap do |session|
          yield session if block_given?
368 369 370 371 372 373
        end
      end

      # Copy the instance variables from the current session instance into the
      # test instance.
      def copy_session_variables! #:nodoc:
374
        return unless integration_session
375
        %w(controller response request).each do |var|
376
          instance_variable_set("@#{var}", @integration_session.__send__(var))
377 378 379
        end
      end

380 381 382 383
      def default_url_options
        reset! unless integration_session
        integration_session.default_url_options
      end
384

385
      def default_url_options=(options)
386
        reset! unless integration_session
387
        integration_session.default_url_options = options
388 389
      end

390
      def respond_to?(method, include_private = false)
391
        integration_session.respond_to?(method, include_private) || super
392 393
      end

394 395
      # Delegate unhandled messages to the current session instance.
      def method_missing(sym, *args, &block)
396 397 398
        reset! unless integration_session
        if integration_session.respond_to?(sym)
          integration_session.__send__(sym, *args, &block).tap do
399 400 401 402
            copy_session_variables!
          end
        else
          super
403 404
        end
      end
405 406 407 408 409

      private
        def integration_session
          @integration_session ||= nil
        end
410
    end
411 412
  end

413
  # An integration test spans multiple controllers and actions,
414 415 416 417
  # 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.
  #
418
  # At its simplest, you simply extend <tt>IntegrationTest</tt> and write your tests
419 420
  # using the get/post methods:
  #
421
  #   require "test_helper"
422
  #
423
  #   class ExampleTest < ActionDispatch::IntegrationTest
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
  #     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
  #       post "/login", :username => people(:jamis).username,
  #         :password => people(:jamis).password
  #       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
443
  # reference any named routes you happen to have defined.
444
  #
445
  #   require "test_helper"
446
  #
447
  #   class AdvancedTest < ActionDispatch::IntegrationTest
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
  #     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!
  #           get(room_url(:id => room.id))
  #           assert(...)
  #           ...
  #         end
  #
  #         def speak(room, message)
  #           xml_http_request "/say/#{room.id}", :message => message
  #           assert(...)
  #           ...
  #         end
  #       end
  #
  #       def login(who)
  #         open_session do |sess|
  #           sess.extend(CustomAssertions)
  #           who = people(who)
  #           sess.post "/login", :username => who.username,
  #             :password => who.password
  #           assert(...)
  #         end
  #       end
  #   end
488
  class IntegrationTest < ActiveSupport::TestCase
489
    include Integration::Runner
490
    include ActionController::TemplateAssertions
491
    include ActionDispatch::Routing::UrlFor
492

493 494 495
    # Use AD::IntegrationTest for acceptance tests
    register_spec_type(/(Acceptance|Integration) ?Test\z/i, self)

496 497 498
    @@app = nil

    def self.app
499 500 501 502 503 504
      if !@@app && !ActionDispatch.test_app
        ActiveSupport::Deprecation.warn "Rails application fallback is deprecated " \
          "and no longer works, please set ActionDispatch.test_app", caller
      end

      @@app || ActionDispatch.test_app
505 506 507 508 509 510 511 512 513
    end

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

    def app
      super || self.class.app
    end
514 515 516 517 518

    def url_options
      reset! unless integration_session
      integration_session.url_options
    end
519
  end
520
end