Class ActionController::Integration::Session
In: actionpack/lib/action_controller/integration.rb
Parent: Object

An integration Session instance represents a set of requests and responses performed sequentially by some virtual user. Becase you can instantiate multiple sessions and run them side-by-side, you can also mimic (to some limited extent) multiple simultaneous users interacting with your system.

Typically, you will instantiate a new session using IntegrationTest#open_session, rather than instantiating Integration::Session directly.

Methods

Included Modules

Test::Unit::Assertions ActionController::Assertions ActionController::TestProcess

Attributes

accept  [RW]  The Accept header to send.
controller  [R]  A reference to the controller instance used by the last request.
cookies  [R]  A map of the cookies returned by the last response, and which will be sent with the next request.
headers  [R]  A map of the headers returned by the last response.
host  [RW]  The hostname used in the last request.
path  [R]  The URI of the last request.
remote_addr  [RW]  The remote_addr used in the last request.
request  [R]  A reference to the request instance used by the last request.
response  [R]  A reference to the response instance used by the last request.
status  [R]  The integer HTTP status code of the last request.
status_message  [R]  The status message that accompanied the status code of the last request.

Public Class methods

Create and initialize a new Session instance.

[Source]

# File actionpack/lib/action_controller/integration.rb, line 55
      def initialize
        reset!
      end

Public Instance methods

Performs a DELETE request with the given parameters. See get() for more details.

[Source]

# File actionpack/lib/action_controller/integration.rb, line 170
      def delete(path, parameters = nil, headers = nil)
        process :delete, path, parameters, headers
      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.

[Source]

# File actionpack/lib/action_controller/integration.rb, line 118
      def follow_redirect!
        raise "not a redirect! #{@status} #{@status_message}" unless redirect?
        get(interpret_uri(headers['location'].first))
        status
      end

Performs a GET request with the given parameters. The parameters may be nil, a Hash, or a string that is appropriately encoded (application/x-www-form-urlencoded or multipart/form-data). The headers should be a hash. The keys will automatically be upcased, with the prefix ‘HTTP_’ added if needed.

You can also perform POST, PUT, DELETE, and HEAD requests with post, put, delete, and head.

[Source]

# File actionpack/lib/action_controller/integration.rb, line 155
      def get(path, parameters = nil, headers = nil)
        process :get, path, parameters, headers
      end

Performs a GET request, 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.

[Source]

# File actionpack/lib/action_controller/integration.rb, line 128
      def get_via_redirect(path, args={})
        get path, args
        follow_redirect! while redirect?
        status
      end

Performs a HEAD request with the given parameters. See get() for more details.

[Source]

# File actionpack/lib/action_controller/integration.rb, line 175
      def head(path, parameters = nil, headers = nil)
        process :head, path, parameters, headers
      end

Set the host name to use in the next request.

  session.host! "www.example.com"

[Source]

# File actionpack/lib/action_controller/integration.rb, line 111
      def host!(name)
        @host = name
      end

Specify whether or not the session should mimic a secure HTTPS request.

  session.https!
  session.https!(false)

[Source]

# File actionpack/lib/action_controller/integration.rb, line 95
      def https!(flag=true)
        @https = flag
      end

Return true if the session is mimicing a secure HTTPS request.

  if session.https?
    ...
  end

[Source]

# File actionpack/lib/action_controller/integration.rb, line 104
      def https?
        @https
      end

Performs a POST request with the given parameters. See get() for more details.

[Source]

# File actionpack/lib/action_controller/integration.rb, line 160
      def post(path, parameters = nil, headers = nil)
        process :post, path, parameters, headers
      end

Performs a POST request, following any subsequent redirect. This is vulnerable to infinite loops, the same as get_via_redirect.

[Source]

# File actionpack/lib/action_controller/integration.rb, line 136
      def post_via_redirect(path, args={})
        post path, args
        follow_redirect! while redirect?
        status
      end

Performs a PUT request with the given parameters. See get() for more details.

[Source]

# File actionpack/lib/action_controller/integration.rb, line 165
      def put(path, parameters = nil, headers = nil)
        process :put, path, parameters, headers
      end

Returns true if the last response was a redirect.

[Source]

# File actionpack/lib/action_controller/integration.rb, line 143
      def redirect?
        status/100 == 3
      end

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!

[Source]

# File actionpack/lib/action_controller/integration.rb, line 64
      def reset!
        @status = @path = @headers = nil
        @result = @status_message = nil
        @https = false
        @cookies = {}
        @controller = @request = @response = nil

        self.host        = "www.example.com"
        self.remote_addr = "127.0.0.1"
        self.accept      = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"

        unless defined? @named_routes_configured
          # install the named routes in this session instance.
          # But we have to disable the optimisation code so that we can
          # generate routes without @request being initialized
          Routing.optimise_named_routes=false
          Routing::Routes.reload!
          klass = class<<self; self; end
          Routing::Routes.install_helpers(klass)

          # the helpers are made protected by default--we make them public for
          # easier access during testing and troubleshooting.
          klass.send(:public, *Routing::Routes.named_routes.helpers)
          @named_routes_configured = true
        end
      end

Returns the URL for the given options, according to the rules specified in the application’s routes.

[Source]

# File actionpack/lib/action_controller/integration.rb, line 197
      def url_for(options)
        controller ? controller.url_for(options) : generic_url_rewriter.rewrite(options)
      end
xhr(request_method, path, parameters = nil, headers = nil)

Alias for xml_http_request

Performs an XMLHttpRequest request with the given parameters, mirroring a request from the Prototype library.

The request_method is :get, :post, :put, :delete or :head; the parameters are nil, a hash, or a url-encoded or multipart string; the headers are a hash. Keys are automatically upcased and prefixed with ‘HTTP_’ if not already.

[Source]

# File actionpack/lib/action_controller/integration.rb, line 186
      def xml_http_request(request_method, path, parameters = nil, headers = nil)
        headers ||= {}
        headers['X-Requested-With'] = 'XMLHttpRequest'
        headers['Accept'] = 'text/javascript, text/html, application/xml, text/xml, */*'

        process(request_method, path, parameters, headers)
      end

Private Instance methods

Encode the cookies hash in a format suitable for passing to a request.

[Source]

# File actionpack/lib/action_controller/integration.rb, line 301
        def encode_cookies
          cookies.inject("") do |string, (name, value)|
            string << "#{name}=#{value}; "
          end
        end

Get a temporary URL writer object

[Source]

# File actionpack/lib/action_controller/integration.rb, line 308
        def generic_url_rewriter
          cgi = MockCGI.new('REQUEST_METHOD' => "GET",
                            'QUERY_STRING'   => "",
                            "REQUEST_URI"    => "/",
                            "HTTP_HOST"      => host,
                            "SERVER_PORT"    => https? ? "443" : "80",
                            "HTTPS"          => https? ? "on" : "off")
          ActionController::UrlRewriter.new(ActionController::CgiRequest.new(cgi), {})
        end

Tailors the session based on the given URI, setting the HTTPS value and the hostname.

[Source]

# File actionpack/lib/action_controller/integration.rb, line 215
        def interpret_uri(path)
          location = URI.parse(path)
          https! URI::HTTPS === location if location.scheme
          host! location.host if location.host
          location.query ? "#{location.path}?#{location.query}" : location.path
        end

[Source]

# File actionpack/lib/action_controller/integration.rb, line 318
        def name_with_prefix(prefix, name)
          prefix ? "#{prefix}[#{name}]" : name.to_s
        end

Parses the result of the response and extracts the various values, like cookies, status, headers, etc.

[Source]

# File actionpack/lib/action_controller/integration.rb, line 281
        def parse_result
          headers, result_body = @result.split(/\r\n\r\n/, 2)

          @headers = Hash.new { |h,k| h[k] = [] }
          headers.each_line do |line|
            key, value = line.strip.split(/:\s*/, 2)
            @headers[key.downcase] << value
          end

          (@headers['set-cookie'] || [] ).each do |string|
            name, value = string.match(/^(.*?)=(.*?);/)[1,2]
            @cookies[name] = value
          end

          @status, @status_message = @headers["status"].first.split(/ /)
          @status = @status.to_i
        end

Performs the actual request.

[Source]

# File actionpack/lib/action_controller/integration.rb, line 223
        def process(method, path, parameters = nil, headers = nil)
          data = requestify(parameters)
          path = interpret_uri(path) if path =~ %r{://}
          path = "/#{path}" unless path[0] == ?/
          @path = path
          env = {}

          if method == :get
            env["QUERY_STRING"] = data
            data = nil
          end

          env.update(
            "REQUEST_METHOD" => method.to_s.upcase,
            "REQUEST_URI"    => path,
            "HTTP_HOST"      => host,
            "REMOTE_ADDR"    => remote_addr,
            "SERVER_PORT"    => (https? ? "443" : "80"),
            "CONTENT_TYPE"   => "application/x-www-form-urlencoded",
            "CONTENT_LENGTH" => data ? data.length.to_s : nil,
            "HTTP_COOKIE"    => encode_cookies,
            "HTTPS"          => https? ? "on" : "off",
            "HTTP_ACCEPT"    => accept
          )

          (headers || {}).each do |key, value|
            key = key.to_s.upcase.gsub(/-/, "_")
            key = "HTTP_#{key}" unless env.has_key?(key) || key =~ /^HTTP_/
            env[key] = value
          end

          unless ActionController::Base.respond_to?(:clear_last_instantiation!)
            ActionController::Base.send(:include, ControllerCapture)
          end

          ActionController::Base.clear_last_instantiation!

          cgi = MockCGI.new(env, data)
          Dispatcher.dispatch(cgi, ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS, cgi.stdoutput)
          @result = cgi.stdoutput.string

          @controller = ActionController::Base.last_instantiation
          @request = @controller.request
          @response = @controller.response

          # Decorate the response with the standard behavior of the TestResponse
          # so that things like assert_response can be used in integration
          # tests.
          @response.extend(TestResponseBehavior)

          @html_document = nil

          parse_result
          return status
        end

Convert the given parameters to a request string. The parameters may be a string, nil, or a Hash.

[Source]

# File actionpack/lib/action_controller/integration.rb, line 324
        def requestify(parameters, prefix=nil)
          if Hash === parameters
            return nil if parameters.empty?
            parameters.map { |k,v| requestify(v, name_with_prefix(prefix, k)) }.join("&")
          elsif Array === parameters
            parameters.map { |v| requestify(v, name_with_prefix(prefix, "")) }.join("&")
          elsif prefix.nil?
            parameters
          else
            "#{CGI.escape(prefix)}=#{CGI.escape(parameters.to_s)}"
          end
        end

[Validate]