Skip to content

Instantly share code, notes, and snippets.

@Rio517
Created March 5, 2018 10:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rio517/df6c5995f6b83fb56bae98e00e46bb22 to your computer and use it in GitHub Desktop.
Save Rio517/df6c5995f6b83fb56bae98e00e46bb22 to your computer and use it in GitHub Desktop.
Allow passing body to in rails test suites
# Overriding ActionDispatch::Integration::Session.any_instance.process
# Adding a body and passing to rack-test as an :input param.
module ActionDispatch
module Integration
class Session
#add body param here
def process(method, path, params: nil, body: nil, headers: nil, env: nil, xhr: false, as: nil)
request_encoder = RequestEncoder.encoder(as)
headers ||= {}
if method == :get && as == :json && params
headers["X-Http-Method-Override"] = "GET"
method = :post
end
if path =~ %r{://}
path = build_expanded_path(path) do |location|
https! URI::HTTPS === location if location.scheme
if url_host = location.host
default = Rack::Request::DEFAULT_PORTS[location.scheme]
url_host += ":#{location.port}" if default != location.port
host! url_host
end
end
end
hostname, port = host.split(":")
puts raw_body
request_env = {
:method => method,
:params => request_encoder.encode_params(params),
# adding a body
:input => body,
"SERVER_NAME" => hostname,
"SERVER_PORT" => port || (https? ? "443" : "80"),
"HTTPS" => https? ? "on" : "off",
"rack.url_scheme" => https? ? "https" : "http",
"REQUEST_URI" => path,
"HTTP_HOST" => host,
"REMOTE_ADDR" => remote_addr,
"CONTENT_TYPE" => request_encoder.content_type,
"HTTP_ACCEPT" => request_encoder.accept_header || accept
}
wrapped_headers = Http::Headers.from_hash({})
wrapped_headers.merge!(headers) if headers
if xhr
wrapped_headers["HTTP_X_REQUESTED_WITH"] = "XMLHttpRequest"
wrapped_headers["HTTP_ACCEPT"] ||= [Mime[:js], Mime[:html], Mime[:xml], "text/xml", "*/*"].join(", ")
end
# This modifies the passed request_env directly.
if wrapped_headers.present?
Http::Headers.from_hash(request_env).merge!(wrapped_headers)
end
if env.present?
Http::Headers.from_hash(request_env).merge!(env)
end
session = Rack::Test::Session.new(_mock_session)
# NOTE: rack-test v0.5 doesn't build a default uri correctly
# Make sure requested path is always a full URI.
session.request(build_full_uri(path, request_env), request_env)
@request_count += 1
@request = ActionDispatch::Request.new(session.last_request.env)
response = _mock_session.last_response
@response = ActionDispatch::TestResponse.from_response(response)
@response.request = @request
@html_document = nil
@url_options = nil
@controller = @request.controller_instance
response.status
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment