Skip to content
This repository
branch: master
file 67 lines (51 sloc) 1.737 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
module Rack

  class MockSession # :nodoc:
    attr_writer :cookie_jar
    attr_reader :default_host

    def initialize(app, default_host = Rack::Test::DEFAULT_HOST)
      @app = app
      @after_request = []
      @default_host = default_host
      @last_request = nil
      @last_response = nil
    end

    def after_request(&block)
      @after_request << block
    end

    def clear_cookies
      @cookie_jar = Rack::Test::CookieJar.new([], @default_host)
    end

    def set_cookie(cookie, uri = nil)
      cookie_jar.merge(cookie, uri)
    end

    def request(uri, env)
      env["HTTP_COOKIE"] ||= cookie_jar.for(uri)
      @last_request = Rack::Request.new(env)
      status, headers, body = @app.call(@last_request.env)

      @last_response = MockResponse.new(status, headers, body, env["rack.errors"].flush)
      body.close if body.respond_to?(:close)

      cookie_jar.merge(last_response.headers["Set-Cookie"], uri)

      @after_request.each { |hook| hook.call }

      if @last_response.respond_to?(:finish)
        @last_response.finish
      else
        @last_response
      end
    end

    # Return the last request issued in the session. Raises an error if no
    # requests have been sent yet.
    def last_request
      raise Rack::Test::Error.new("No request yet. Request a page first.") unless @last_request
      @last_request
    end

    # Return the last response received in the session. Raises an error if
    # no requests have been sent yet.
    def last_response
      raise Rack::Test::Error.new("No response yet. Request a page first.") unless @last_response
      @last_response
    end

    def cookie_jar
      @cookie_jar ||= Rack::Test::CookieJar.new([], @default_host)
    end

  end

end
Something went wrong with that request. Please try again.