5 require 'rack/response'
8 # Rack::MockRequest helps testing your Rack application without
11 # After performing a request on a URL with get/post/put/delete, it
12 # returns a MockResponse with useful helper methods for effective
15 # You can pass a hash with additional configuration to the
16 # get/post/put/delete.
17 # <tt>:input</tt>:: A String or IO-like to be used as rack.input.
18 # <tt>:fatal</tt>:: Raise a FatalWarning if the app writes to rack.errors.
19 # <tt>:lint</tt>:: If true, wrap the application in a Rack::Lint.
22 class FatalWarning
< RuntimeError
27 raise FatalWarning
, warning
31 raise FatalWarning
, warning
43 "rack.version" => [0,1],
44 "rack.input" => StringIO
.new
,
45 "rack.errors" => StringIO
.new
,
46 "rack.multithread" => true,
47 "rack.multiprocess" => true,
48 "rack.run_once" => false,
55 def get(uri
, opts
={}) request("GET", uri
, opts
) end
56 def post(uri
, opts
={}) request("POST", uri
, opts
) end
57 def put(uri
, opts
={}) request("PUT", uri
, opts
) end
58 def delete(uri
, opts
={}) request("DELETE", uri
, opts
) end
60 def request(method
="GET", uri
="", opts
={})
61 env = self.class.env_for(uri
, opts
.merge(:method => method
))
64 app
= Rack
::Lint.new(@app)
69 errors
= env["rack.errors"]
70 MockResponse
.new(*(app
.call(env) + [errors
]))
73 # Return the Rack environment used for a request to +uri+.
74 def self.env_for(uri
="", opts
={})
78 env["REQUEST_METHOD"] = opts
[:method] || "GET"
79 env["SERVER_NAME"] = uri
.host
|| "example.org"
80 env["SERVER_PORT"] = uri
.port
? uri
.port
.to_s
: "80"
81 env["QUERY_STRING"] = uri
.query
.to_s
82 env["PATH_INFO"] = (!uri
.path
|| uri
.path
.empty
?) ? "/" : uri
.path
83 env["rack.url_scheme"] = uri
.scheme
|| "http"
85 env["SCRIPT_NAME"] = opts
[:script_name] || ""
88 env["rack.errors"] = FatalWarner
.new
90 env["rack.errors"] = StringIO
.new
94 if String
=== opts
[:input]
95 env["rack.input"] = StringIO
.new(opts
[:input])
97 env["rack.input"] = opts
[:input]
100 env["CONTENT_LENGTH"] ||= env["rack.input"].length
.to_s
102 opts
.each
{ |field
, value
|
103 env[field
] = value
if String
=== field
110 # Rack::MockResponse provides useful helpers for testing your apps.
111 # Usually, you don't create the MockResponse on your own, but use
115 def initialize(status
, headers
, body
, errors
=StringIO
.new(""))
116 @status = status
.to_i
118 @original_headers = headers
119 @headers = Rack
::Utils::HeaderHash.new
120 headers
.each
{ |field
, values
|
121 @headers[field
] = values
122 @headers[field
] = "" if values
.empty
?
126 body
.each
{ |part
| @body << part
}
128 @errors = errors
.string
135 attr_reader
:headers, :original_headers
155 attr_accessor
:errors
158 include Response
::Helpers