サンプル
rack-test 2.2.0: Manage Rack::Test per-request CGI environment keys, session header persistence, JSON string Content-Type defaults, UploadedFile multipart symbol params, and redirect method preservation
検証済みサンプル — gem rack-test 2.2.0: Manage Rack::Test per-request CGI environment keys, session header persistence, JSON string Content-Type defaults…
sha256:4a97ed0ea867bda6aee5fa0441787f219f66cdcc3c2001ec445a64d8b10003a1
このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。
合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。
MIT-0
実行証拠
宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。
- 証拠の基準
- 署名済みコントラクト合格
- 検証レシート
- 2
- ビルドした署名鍵
- 1
宣言された環境
ruby linux x64 ruby ruby rubygems
検証実行環境
| 環境 | コントラクト | ステージ | 実行日 |
|---|---|---|---|
| ruby 3 · linux debian/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · rubygems@1 |
2026-08-16 |
| ruby 3 · linux debian/x64 · docker ed25519:2175b912ea1c23b1 | SKIPPED | compile:SKIPPED · contract:SKIPPED · load:SKIPPED · resolve:FAIL CONTAINER_RUN · rubygems@1 |
2026-08-18 |
ケース
HOW- ゴール
- Manage Rack::Test per-request CGI environment keys, session header persistence, JSON string Content-Type defaults, UploadedFile multipart symbol params, and redirect method preservation
- パッケージ
- シンボル
-
- Rack::Test::Methods
- Rack::Test::Session#header
- Rack::Test::Session#get
- Rack::Test::Session#post
- Rack::Test::Session#follow_redirect!
- Rack::Test::UploadedFile.new
- Rack::Test::CookieJar
- 環境
- ruby
- 作成日
- 2026-08-16T17:46:56Z
コントラクト
- assert passing raw HTTP header names in the third argument leaves them un-prefixed in env rather than transforming to HTTP_ CGI keys
- assert session header helper transforms names to HTTP_ CGI keys and persists them across subsequent requests until explicitly cleared
- assert posting a raw String body defaults Content-Type to application/x-www-form-urlencoded and form-parses the payload unless overridden
- assert UploadedFile wrapping a StringIO requires original_filename as a keyword argument and transforms params into multipart symbol-keyed Hashes
- assert follow_redirect raises on non-redirects, converts 302 to GET with empty params, and preserves 307 request method and params
- assert cookies without an explicit domain match only the exact host and expired cookies are omitted from subsequent requests
ファイル
- Gemfile
- NOTES.md
- csx.json
- src/app.rb
- test/contract.rb
ソース
source "https://rubygems.org"
gem "rack-test", "2.2.0"
gem "rack", "3.2.7"
gem "minitest", "5.27.0"
# Notes on `pkg:gem/rack-test` Contract
## 1. What `search_known_solution` answered
`search_known_solution` returned a match for sample `sha256:cb16ec9117c9887155c2792e1e4607e740fe8c584754b3d6136855be6762490b` ("Test a Sinatra 4 app with rack-test in the same process, with no server, and get the params, filter and 404 behaviour right instead of guessing it"). That sample evaluated Sinatra 4 framework integrations (modular versus classic base classes, HostAuthorization middleware blocking requests with 403, parameter precedence between route captures, query strings, and form bodies, filter halting with `halt` versus `return`, and custom 404 views).
This sample focuses directly on the core `Rack::Test` library API contracts and traps: per-request CGI environment keys versus session header persistence, default Content-Type handling on raw String payloads, `Rack::Test::UploadedFile` keyword argument requirements and multipart parameter transformation, redirect method preservation semantics between HTTP 302 and 307, and `CookieJar` domain scoping.
## 2. What a model would have written instead
- Passed per-request HTTP headers as a third argument to request methods using standard header names (e.g. `get("/api", {}, { "Authorization" => "Bearer secret" })`), expecting `Rack::Test` to translate them into standard Rack environment keys.
- Assumed `header("X-Token", "secret")` applies only to the subsequent request rather than mutating persistent session state.
- Passed a raw JSON string to `post("/api", '{"id":1}')` expecting `Rack::Test` to detect JSON or leave Content-Type empty.
- Initialized `Rack::Test::UploadedFile.new(StringIO.new("..."), "text/plain")` with positional arguments or omitted the filename, and expected `params["file"]` in the application to be an `UploadedFile` instance.
- Assumed `follow_redirect!` preserves HTTP POST methods across standard 302 redirects.
- Assumed cookies set without an explicit domain attribute are sent to subdomains.
## 3. How the wrong version fails
- **Loud failures**:
- `Rack::Test::UploadedFile.new(StringIO.new("data"), "text/plain")` raises `ArgumentError: Missing 'original_filename' for StringIO object` because `original_filename:` is a required keyword argument when wrapping an `IO` or `StringIO`.
- Calling `follow_redirect!` when the prior response returned 200 OK raises `Rack::Test::Error: Last response was not a redirect. Cannot follow_redirect!`.
- **Silent failures with green build**:
- Passing `{ "X-Token" => "secret" }` in the third `env` argument silently leaves `"X-Token"` as an un-prefixed environment key while `env["HTTP_X_TOKEN"]` remains `nil`, causing downstream authentication middleware or endpoints reading `HTTP_X_TOKEN` to fail silently.
- `header("X-Token", "secret")` silently mutates `@env` in the session, leaking headers to all subsequent requests across test cases unless cleared with `header("X-Token", nil)`.
- Calling `post` with a raw string body silently defaults `CONTENT_TYPE` to `application/x-www-form-urlencoded`, causing Rack to parse the string payload as form keys (`{ '{"name":"alice"}' => nil }`) rather than leaving `params` empty.
- `follow_redirect!` on an HTTP 302 response silently switches the HTTP method from `POST` to `GET` and discards all request body parameters.
{"case":{"believed":"Passing an HTTP header dictionary as the third argument to Rack::Test request methods translates header names into Rack environment keys for that single request.","caseId":"case:sha256:b2838bca11d3c431dcf420a3b19c9c8593785a506afe9774cb9b14329fa2a108","contract":["assert passing raw HTTP header names in the third argument leaves them un-prefixed in env rather than transforming to HTTP_ CGI keys","assert session header helper transforms names to HTTP_ CGI keys and persists them across subsequent requests until explicitly cleared","assert posting a raw String body defaults Content-Type to application/x-www-form-urlencoded and form-parses the payload unless overridden","assert UploadedFile wrapping a StringIO requires original_filename as a keyword argument and transforms params into multipart symbol-keyed Hashes","assert follow_redirect raises on non-redirects, converts 302 to GET with empty params, and preserves 307 request method and params","assert cookies without an explicit domain match only the exact host and expired cookies are omitted from subsequent requests"],"goal":"Manage Rack::Test per-request CGI environment keys, session header persistence, JSON string Content-Type defaults, UploadedFile multipart symbol params, and redirect method preservation","kind":"HOW","packages":["pkg:gem/rack-test@2.2.0","pkg:gem/rack@3.2.7"],"schemaVersion":1,"symbols":["Rack::Test::Methods","Rack::Test::Session#header","Rack::Test::Session#get","Rack::Test::Session#post","Rack::Test::Session#follow_redirect!","Rack::Test::UploadedFile.new","Rack::Test::CookieJar"]},"contractCommand":["ruby","test/contract.rb"],"environment":{"arch":"x64","ecosystem":"gem","executionContext":"ruby","language":"ruby","os":"linux","packageManager":"rubygems","runtime":"ruby","schemaVersion":1},"license":"MIT-0","packages":["pkg:gem/rack-test@2.2.0","pkg:gem/rack@3.2.7"],"schemaVersion":1,"symbols":["Rack::Test::Methods","Rack::Test::Session#header","Rack::Test::Session#get","Rack::Test::Session#post","Rack::Test::Session#follow_redirect!","Rack::Test::UploadedFile.new","Rack::Test::CookieJar"],"verifierAdapter":"rubygems@1"}
# frozen_string_literal: true
require "rack"
require "json"
module RackTestContract
class RecordingApp
attr_reader :last_recorded
def initialize
@last_recorded = nil
end
def call(env)
req = Rack::Request.new(env)
raw_body = ""
if env["rack.input"]
raw_body = env["rack.input"].read
env["rack.input"].rewind
end
# Capture what Rack and the application actually see
@last_recorded = {
method: req.request_method,
path: req.path_info,
host: req.host,
query_string: req.query_string,
params: req.params,
cookies: req.cookies,
content_type: req.content_type,
content_length: req.content_length,
http_x_token: env["HTTP_X_TOKEN"],
raw_x_token: env["X-Token"],
http_referer: env["HTTP_REFERER"],
rack_test_flag: env["rack.test"],
body: raw_body
}
case req.path_info
when "/redirect-302"
[
302,
{
"location" => "/landed",
"set-cookie" => "auth_session=token_abc; path=/"
},
["Moved Temporarily"]
]
when "/redirect-307"
[
307,
{ "location" => "/landed" },
["Temporary Redirect"]
]
when "/cookie-set"
[
200,
{
"content-type" => "text/plain",
"set-cookie" => "host_only=val1; path=/\ndomain_wide=val2; domain=example.org; path=/"
},
["Cookies set"]
]
when "/cookie-expire"
[
200,
{
"content-type" => "text/plain",
"set-cookie" => "host_only=; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"
},
["Cookie expired"]
]
when "/landed"
[
200,
{ "content-type" => "application/json" },
[JSON.generate(@last_recorded)]
]
when "/upload"
[
200,
{ "content-type" => "application/json" },
[JSON.generate({ status: "uploaded", params_keys: req.params.keys })]
]
else
[
200,
{ "content-type" => "application/json" },
[JSON.generate(@last_recorded)]
]
end
end
end
end
# frozen_string_literal: true
require "minitest/autorun"
require "rack"
require "rack/test"
require "stringio"
require_relative "../src/app"
class RackTestContractTest < Minitest::Test
include Rack::Test::Methods
attr_reader :app_instance
def app
@app_instance ||= RackTestContract::RecordingApp.new
end
def setup
@app_instance = RackTestContract::RecordingApp.new
end
# 1. The env argument trap: 3rd parameter is a CGI env hash, NOT an HTTP header map
def test_passing_raw_http_header_names_in_env_leaves_them_unprefixed
# Naive assumption: get(path, params, headers) maps "X-Token" to HTTP_X_TOKEN.
# Reality: The 3rd argument is merged directly into Rack env. "X-Token" is kept
# as a non-standard env key, while HTTP_X_TOKEN remains nil.
get "/inspect", {}, { "X-Token" => "env-token" }
assert_nil app_instance.last_recorded[:http_x_token]
assert_equal "env-token", app_instance.last_recorded[:raw_x_token]
assert_equal true, app_instance.last_recorded[:rack_test_flag]
# To pass per-request headers via the 3rd argument, callers must supply the CGI key:
get "/inspect", {}, { "HTTP_X_TOKEN" => "cgi-token" }
assert_equal "cgi-token", app_instance.last_recorded[:http_x_token]
end
# 2. Session header helper transforms names and persists across requests
def test_session_header_transforms_to_cgi_and_persists_until_cleared
# header helper transforms name to HTTP_... and stores in session @env
header "X-Token", "session-secret"
get "/first"
assert_equal "session-secret", app_instance.last_recorded[:http_x_token]
# Persists across subsequent requests without repeating the header call
get "/second"
assert_equal "session-secret", app_instance.last_recorded[:http_x_token]
# Must be explicitly cleared with nil to remove from session state
header "X-Token", nil
get "/third"
assert_nil app_instance.last_recorded[:http_x_token]
end
# 3. Raw String POST body defaults Content-Type to form-urlencoded
def test_post_string_defaults_to_form_urlencoded_and_parses_as_form_data
# Naive assumption: passing a JSON string auto-detects application/json or leaves type unset.
# Reality: Rack::Test defaults CONTENT_TYPE to application/x-www-form-urlencoded,
# causing Rack to attempt form parsing and corrupt params with the JSON string as a key.
post "/api/json", '{"name":"alice"}'
assert_equal "application/x-www-form-urlencoded", app_instance.last_recorded[:content_type]
assert_includes app_instance.last_recorded[:params].keys, '{"name":"alice"}'
assert_equal '{"name":"alice"}', app_instance.last_recorded[:body]
# Explicit application/json Content-Type prevents form-mangling (params is empty in pure Rack)
header "Content-Type", "application/json"
post "/api/json-proper", '{"name":"alice"}'
assert_equal "application/json", app_instance.last_recorded[:content_type]
assert_equal({}, app_instance.last_recorded[:params])
assert_equal '{"name":"alice"}', app_instance.last_recorded[:body]
header "Content-Type", nil
end
# 4. UploadedFile keyword argument requirements and multipart symbol params
def test_uploaded_file_from_stringio_and_multipart_symbol_hash_params
# StringIO requires original_filename as a keyword argument (positional fails with ArgumentError)
assert_raises(ArgumentError) do
Rack::Test::UploadedFile.new(StringIO.new("file-data"), "text/plain")
end
uploaded = Rack::Test::UploadedFile.new(
StringIO.new("file-content"),
"text/plain",
original_filename: "doc.txt"
)
post "/upload", { "title" => "Documentation", "file" => uploaded }
# Triggers multipart content-type boundary
assert_match(%r{\Amultipart/form-data; boundary=}, app_instance.last_recorded[:content_type])
assert_equal "Documentation", app_instance.last_recorded[:params]["title"]
# Inside the Rack app, params["file"] is a Hash with symbol keys, NOT an UploadedFile
file_param = app_instance.last_recorded[:params]["file"]
assert_instance_of Hash, file_param
assert_equal "doc.txt", file_param[:filename]
assert_equal "text/plain", file_param[:type]
assert_equal "file-content", file_param[:tempfile].read
end
# 5. follow_redirect! mechanics and HTTP 302 vs 307 method preservation
def test_follow_redirect_converts_302_to_get_and_preserves_307_method_and_params
# Calling follow_redirect! on non-redirect response raises Rack::Test::Error
get "/inspect"
assert_equal 200, last_response.status
assert_raises(Rack::Test::Error) do
follow_redirect!
end
# 302 Found: converts POST to GET, clears params, forwards cookies, and sets HTTP_REFERER
post "/redirect-302", { "sensitive" => "data" }
assert_equal 302, last_response.status
assert_equal true, last_response.redirect?
follow_redirect!
assert_equal 200, last_response.status
assert_equal "GET", app_instance.last_recorded[:method]
assert_equal "/landed", app_instance.last_recorded[:path]
assert_equal({}, app_instance.last_recorded[:params])
assert_equal "token_abc", app_instance.last_recorded[:cookies]["auth_session"]
assert_equal "http://example.org/redirect-302", last_request.env["HTTP_REFERER"]
# 307 Temporary Redirect: preserves POST method and request params
post "/redirect-307", { "payload" => "persist-body" }
assert_equal 307, last_response.status
follow_redirect!
assert_equal 200, last_response.status
assert_equal "POST", app_instance.last_recorded[:method]
assert_equal "persist-body", app_instance.last_recorded[:params]["payload"]
end
# 6. CookieJar domain scoping and expired cookie omission
def test_cookie_domain_scoping_and_expired_cookie_lifecycle
get "/cookie-set"
assert_equal "val1", current_session.cookie_jar["host_only"]
assert_equal "val2", current_session.cookie_jar["domain_wide"]
# Requests to default host (example.org) receive both host-only and domain-scoped cookies
get "/inspect"
assert_equal({ "host_only" => "val1", "domain_wide" => "val2" }, app_instance.last_recorded[:cookies])
# Requests to subdomain receive only the domain-scoped cookie
get "http://sub.example.org/inspect"
assert_equal({ "domain_wide" => "val2" }, app_instance.last_recorded[:cookies])
# Expiring cookie via Set-Cookie max-age=0 marks cookie expired and excludes it from future requests
get "/cookie-expire"
get "/inspect"
assert_equal({ "domain_wide" => "val2" }, app_instance.last_recorded[:cookies])
assert_equal true, current_session.cookie_jar.get_cookie("host_only").expired?
end
end