Module: Merb::Test::MakeRequest

Included in:
RequestHelper
Defined in:
lib/merb-core/test/helpers/request_helper.rb

Instance Method Summary collapse

Instance Method Details

#request(uri, env = {}) ⇒ Object



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
# File 'lib/merb-core/test/helpers/request_helper.rb', line 7

def request(uri, env = {})
  uri = url(uri) if uri.is_a?(Symbol)
  uri = URI(trim_prefix(uri))
  uri.scheme ||= "http"
  uri.host   ||= "example.org"

  if (env[:method] == "POST" || env["REQUEST_METHOD"] == "POST")
    params = env.delete(:body_params) if env.key?(:body_params)
    params = env.delete(:params) if env.key?(:params) && !env.key?(:input)

    unless env.key?(:input)
      env[:input] = Merb::Parse.params_to_query_string(params)
      env["CONTENT_TYPE"] = "application/x-www-form-urlencoded"
    end
  end

  if env[:params]
    uri.query = [
      uri.query, Merb::Parse.params_to_query_string(env.delete(:params))
    ].compact.join("&")
  end
  
  ignore_cookies = env.has_key?(:jar) && env[:jar].nil?

  unless ignore_cookies
    # Setup a default cookie jar container
    @__cookie_jar__ ||= Merb::Test::CookieJar.new
    # Grab the cookie group name
    jar = env.delete(:jar) || :default
    # Add the cookies explicitly set by the user
    @__cookie_jar__.update(jar, uri, env.delete(:cookie)) if env.has_key?(:cookie)
    # Set the cookie header with the cookies
    env["HTTP_COOKIE"] = @__cookie_jar__.for(jar, uri)
  end
  
  app = Merb::Config[:app]
  rack = app.call(::Rack::MockRequest.env_for(uri.to_s, env))

  rack = Struct.new(:status, :headers, :body, :url, :original_env).
    new(rack[0], rack[1], rack[2], uri.to_s, env)
    
  @__cookie_jar__.update(jar, uri, rack.headers["Set-Cookie"]) unless ignore_cookies

  Merb::Dispatcher.work_queue.size.times do
    Merb::Dispatcher.work_queue.pop.call
  end

  rack
end