Пример
faraday 2.11.0: Test Faraday code against stubbed HTTP with no network, and work out which parts of Faraday 2 still need an extra gem
Проверенный пример — gem faraday 2.11.0: Test Faraday code against stubbed HTTP with no network, and work out which parts of Faraday 2 still need an extra…
sha256:46eed9d91592cb5df8548ed6884a818eba294fbab879f42106d919a145b91d8a
Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла.
Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди.
MIT-0
Свидетельства выполнения
Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.
- Основа свидетельства
- Подписанный контракт пройден
- Квитанции проверки
- 2
- Ключи подписи, собравшие его
- 2
Заявленная среда
ruby 3 linux x64 ruby 3 ruby bundler
Среды запусков проверки
| Окружение | Контракт | Этапы | Запуск |
|---|---|---|---|
| ruby 3 · linux alpine/x64 · docker ed25519:a2ec939a4c60e243 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · gem@1 |
2026-08-14 |
| ruby 3 · linux debian/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · gem@1 |
2026-08-18 |
Кейс
HOW- Цель
- Test Faraday code against stubbed HTTP with no network, and work out which parts of Faraday 2 still need an extra gem
- Символы
-
- Faraday::Adapter::Test
- Faraday::Adapter::Test::Stubs
- Faraday::Response::Json
- Faraday::Response::RaiseError
- Faraday::ServerError
- Faraday::ResourceNotFound
- Окружение
- ruby 3
- Создан
- 2026-08-14T09:45:11Z
Контракт
- assert a Faraday::Adapter::Test stub matching path and query serves the whole connection with no socket
- assert a query the stub declared has to match exactly, while a parameter it did not name is ignored and a stub with no query matches every query
- assert an unmatched request raises Faraday::Adapter::Test::Stubs::NotFound naming the URL
- assert the host from the connection url_prefix reaches the matcher, so a stub written for another host does not match
- assert a 500 without raise_error is only a response, and with raise_error is a Faraday::ServerError
- assert middleware order decides whether the raised error carries a parsed or a raw body
- assert raise_error maps a 404 to Faraday::ResourceNotFound
- assert a JSON body stays a String until the json middleware is added, and then only on a JSON content type
- assert verify_stubbed_calls raises on a stub that went unused, while a consumed stub still answers a repeat call
- assert the test adapter and the json and raise_error middleware ship inside faraday itself
- assert the default net_http adapter is a separate gem, an unregistered adapter fails at lookup, and the default adapter really opens a socket
- assert no json gem is resolved into the bundle, because faraday 2.11 parses with the json Ruby ships
Файлы
- Gemfile
- Gemfile.lock
- csx.json
- src/api.rb
- test/contract.rb
Исходный код
source "https://rubygems.org"
# faraday 2.12 added a runtime dependency on the json gem, and json builds a C
# extension. A ruby alpine image carries no compiler, so on Alpine every
# faraday >= 2.12 dies in extconf during bundle install, before a line of your
# code runs. 2.11.0 is the newest release that stays pure Ruby; its json
# middleware requires Ruby's built-in json instead. Measured, not assumed: the
# same install with 2.14.3 fails on json, and adding build-base is the other
# way out if you control the image.
gem "faraday", "2.11.0"
# minitest 5 for the same reason — minitest 6 depends on prism, another
# C extension gem.
gem "minitest", "5.27.0"
GEM
remote: https://rubygems.org/
specs:
faraday (2.11.0)
faraday-net_http (>= 2.0, < 3.4)
logger
faraday-net_http (3.3.0)
net-http
logger (1.7.0)
minitest (5.27.0)
net-http (0.9.1)
uri (>= 0.11.1)
uri (1.1.1)
PLATFORMS
ruby
x86_64-linux-musl
DEPENDENCIES
faraday (= 2.11.0)
minitest (= 5.27.0)
CHECKSUMS
bundler (4.0.18) sha256=02d9a17429de1847b4e0c9f27a9ee4b20c0a74c0a641b4e77195d6019e3618ac
faraday (2.11.0) sha256=e6ead2c9aa1304107d3bb342e9f930cf7e649a71e3ec1e782c3256672f19ed02
faraday-net_http (3.3.0) sha256=93e6b0f679b1e8e358bcb4e983a52328dfc47ebbe6a232e4f9e8aba9c924e565
logger (1.7.0) sha256=196edec7cc44b66cfb40f9755ce11b392f21f7967696af15d274dde7edff0203
minitest (5.27.0) sha256=2d3b17f8a36fe7801c1adcffdbc38233b938eb0b4966e97a6739055a45fa77d5
net-http (0.9.1) sha256=25ba0b67c63e89df626ed8fac771d0ad24ad151a858af2cc8e6a716ca4336996
uri (1.1.1) sha256=379fa58d27ffb1387eaada68c749d1426738bd0f654d812fcc07e7568f5c57c6
BUNDLED WITH
4.0.18
{"case":{"caseId":"case:sha256:1c8ebe08d179b2355556694606189b6b5cf0615403b1194d2b57e925d8c0d3c3","constraints":{"runtime":"ruby"},"contract":["assert a Faraday::Adapter::Test stub matching path and query serves the whole connection with no socket","assert a query the stub declared has to match exactly, while a parameter it did not name is ignored and a stub with no query matches every query","assert an unmatched request raises Faraday::Adapter::Test::Stubs::NotFound naming the URL","assert the host from the connection url_prefix reaches the matcher, so a stub written for another host does not match","assert a 500 without raise_error is only a response, and with raise_error is a Faraday::ServerError","assert middleware order decides whether the raised error carries a parsed or a raw body","assert raise_error maps a 404 to Faraday::ResourceNotFound","assert a JSON body stays a String until the json middleware is added, and then only on a JSON content type","assert verify_stubbed_calls raises on a stub that went unused, while a consumed stub still answers a repeat call","assert the test adapter and the json and raise_error middleware ship inside faraday itself","assert the default net_http adapter is a separate gem, an unregistered adapter fails at lookup, and the default adapter really opens a socket","assert no json gem is resolved into the bundle, because faraday 2.11 parses with the json Ruby ships"],"goal":"Test Faraday code against stubbed HTTP with no network, and work out which parts of Faraday 2 still need an extra gem","kind":"HOW","packages":["pkg:gem/faraday@2.11.0","pkg:gem/faraday-net_http@3.3.0"],"schemaVersion":1,"symbols":["Faraday::Adapter::Test","Faraday::Adapter::Test::Stubs","Faraday::Response::Json","Faraday::Response::RaiseError","Faraday::ServerError","Faraday::ResourceNotFound"]},"contractCommand":["bundle","exec","ruby","test/contract.rb"],"environment":{"arch":"x64","ecosystem":"gem","executionContext":"ruby","language":"ruby","os":"linux","packageManager":"bundler","runtime":"ruby","runtimeVersion":"3","schemaVersion":1},"license":"MIT-0","packages":["pkg:gem/faraday@2.11.0","pkg:gem/faraday-net_http@3.3.0"],"schemaVersion":1,"symbols":["Faraday::Adapter::Test","Faraday::Adapter::Test::Stubs","Faraday::Response::Json","Faraday::Response::RaiseError","Faraday::ServerError","Faraday::ResourceNotFound"],"verifierAdapter":"gem@1"}
# Testing Faraday code without a network, and what Faraday 2 actually took
# out of core.
#
# The advice you find for Faraday 2 is "adapters and middleware moved out of
# core, so install the extra gems". Half of that is wrong, and guessing which
# half costs you a Gemfile full of gems that do not exist. Faraday::Adapter::Test
# and the json / raise_error response middleware all ship inside faraday
# itself; what moved out is the *default* adapter, net_http, which faraday
# still pulls in as a dependency. The contract measures where each of those
# classes is loaded from instead of taking anyone's word for it.
#
# The test adapter is the Ruby equivalent of an httpx MockTransport: it
# replaces only the bottom of the stack, so url_prefix, query encoding and
# every middleware you registered still run for real.
#
# Two things Faraday does not do for you, both of which look like the
# adapter misbehaving: it does not parse a JSON body (that is
# `f.response :json`, and even then only when the response carries a JSON
# content type) and it does not raise on a 5xx (that is
# `f.response :raise_error`).
require "faraday"
module Api
# A connection that never opens a socket. Middleware order is deliberate:
# response middleware runs bottom-up, so raise_error registered first —
# outermost — sees the body json already parsed.
def self.build(stubs, json: false, raise_error: false)
Faraday.new(url: "https://api.example.com") do |f|
f.response :raise_error if raise_error
f.response :json if json
f.adapter :test, stubs
end
end
def self.fetch_items(conn, page)
conn.get("/items", { "page" => page.to_s })
end
# Which installed gem physically ships a class, resolved from the file the
# method was defined in. This is the only honest way to answer "do I need
# another gem for this".
def self.shipping_gem(klass, method_name)
file, = klass.instance_method(method_name).source_location
spec = Gem.loaded_specs.values.find { |s| file.start_with?(s.full_gem_path) }
spec ? "#{spec.name}-#{spec.version}" : file
end
end
require "minitest/autorun"
require_relative "../src/api"
class FaradayTestAdapterContract < Minitest::Test
Stubs = Faraday::Adapter::Test::Stubs
JSON_BODY = '{"items":[1,2],"page":"2"}'.freeze
JSON_TYPE = { "content-type" => "application/json" }.freeze
def test_stub_matches_on_path_and_query
stubs = Stubs.new do |stub|
stub.get("/items?page=2") { [200, JSON_TYPE, JSON_BODY] }
end
res = Api.fetch_items(Api.build(stubs, json: true), 2)
assert_equal 200, res.status
assert res.success?
assert_equal({ "items" => [1, 2], "page" => "2" }, res.body)
stubs.verify_stubbed_calls
end
def test_a_query_the_stub_declared_must_match_exactly
# The stub's query is a filter, not a description: a request whose page
# is 3 does not reach a stub written for page=2, and the failure is a
# NotFound that names the URL rather than a wrong-looking response.
stubs = Stubs.new do |stub|
stub.get("/items?page=2") { [200, JSON_TYPE, JSON_BODY] }
end
err = assert_raises(Stubs::NotFound) { Api.fetch_items(Api.build(stubs), 3) }
assert_match(/page=3/, err.message)
end
def test_stub_params_are_a_subset_filter_not_an_exact_match
# The asymmetry that catches people: only the keys the stub names are
# compared, so a stub is a filter over the request and never a
# description of it. A stub written without a query is a wildcard over
# every query string, and a stub written for page=2 still answers a
# request that also sent sort=asc. Leaving the query off does not
# tighten the test, it loosens it.
wildcard = Stubs.new { |stub| stub.get("/items") { [200, JSON_TYPE, JSON_BODY] } }
assert_equal 200, Api.fetch_items(Api.build(wildcard), 99).status
partial = Stubs.new { |stub| stub.get("/items?page=2") { [200, JSON_TYPE, JSON_BODY] } }
conn = Api.build(partial)
assert_equal 200, conn.get("/items", { "page" => "2", "sort" => "asc" }).status
end
def test_an_unstubbed_path_raises_not_found
stubs = Stubs.new { |stub| stub.get("/items") { [200, JSON_TYPE, JSON_BODY] } }
err = assert_raises(Stubs::NotFound) { Api.build(stubs).get("/other") }
assert_match(%r{/other}, err.message)
end
def test_the_connection_url_prefix_reaches_the_matcher
# The adapter replaces only the bottom of the stack, so by the time
# matching runs the host from url_prefix is already part of the request:
# a stub written as a full URL matches, and the same stub aimed at
# another host does not. Worth writing that way once a suite talks to
# two services, since a bare path stub answers for either of them.
here = Stubs.new do |stub|
stub.get("https://api.example.com/items") { [200, JSON_TYPE, JSON_BODY] }
end
assert_equal 200, Api.build(here).get("/items").status
elsewhere = Stubs.new do |stub|
stub.get("https://other.example.com/items") { [200, JSON_TYPE, JSON_BODY] }
end
err = assert_raises(Stubs::NotFound) { Api.build(elsewhere).get("/items") }
assert_match(%r{https://api\.example\.com/items}, err.message)
end
def test_a_500_without_raise_error_is_only_a_response
stubs = Stubs.new { |stub| stub.get("/boom") { [500, JSON_TYPE, '{"error":"nope"}'] } }
res = Api.build(stubs, json: true).get("/boom")
refute res.success?
assert_equal 500, res.status
assert_equal({ "error" => "nope" }, res.body)
end
def test_raise_error_turns_the_500_into_a_server_error
stubs = Stubs.new { |stub| stub.get("/boom") { [500, JSON_TYPE, '{"error":"nope"}'] } }
err = assert_raises(Faraday::ServerError) do
Api.build(stubs, json: true, raise_error: true).get("/boom")
end
assert_kind_of Faraday::Error, err
assert_equal 500, err.response[:status]
# raise_error is registered outermost, so json has already run by the
# time it fires and the body on the exception is parsed.
assert_equal({ "error" => "nope" }, err.response[:body])
end
def test_middleware_order_decides_what_the_exception_carries
# Response middleware completes innermost-first. Put raise_error closest
# to the adapter and it wins the race against json, so the exception
# carries the raw string — the same code, reordered, reports differently.
stubs = Stubs.new { |stub| stub.get("/boom") { [500, JSON_TYPE, '{"error":"nope"}'] } }
conn = Faraday.new(url: "https://api.example.com") do |f|
f.response :json
f.response :raise_error
f.adapter :test, stubs
end
err = assert_raises(Faraday::ServerError) { conn.get("/boom") }
assert_equal '{"error":"nope"}', err.response[:body]
end
def test_a_404_maps_to_its_own_subclass
stubs = Stubs.new { |stub| stub.get("/gone") { [404, JSON_TYPE, "{}"] } }
conn = Api.build(stubs, raise_error: true)
err = assert_raises(Faraday::ResourceNotFound) { conn.get("/gone") }
assert_equal 404, err.response[:status]
end
def test_json_is_not_parsed_unless_you_add_the_middleware
stubs = Stubs.new { |stub| stub.get("/items") { [200, JSON_TYPE, JSON_BODY] } }
body = Api.build(stubs).get("/items").body
assert_instance_of String, body
assert_equal JSON_BODY, body
end
def test_the_json_middleware_needs_a_json_content_type
# Second half of the same trap: the middleware is registered but the
# stub returned no content type, so nothing parses and you are back to a
# String. Stubs have to set the header the real server would.
stubs = Stubs.new { |stub| stub.get("/items") { [200, {}, JSON_BODY] } }
assert_instance_of String, Api.build(stubs, json: true).get("/items").body
end
def test_verify_stubbed_calls_fails_on_a_stub_that_went_unused
stubs = Stubs.new do |stub|
stub.get("/items") { [200, JSON_TYPE, JSON_BODY] }
stub.get("/never-called") { [200, JSON_TYPE, JSON_BODY] }
end
conn = Api.build(stubs)
conn.get("/items")
err = assert_raises(RuntimeError) { stubs.verify_stubbed_calls }
assert_match(%r{/never-called}, err.message)
end
def test_a_consumed_stub_still_answers_a_second_identical_call
# Matched stubs are moved to a consumed list, not deleted, so a retry
# loop under test does not fall off a cliff on the second attempt.
stubs = Stubs.new { |stub| stub.get("/items") { [200, JSON_TYPE, JSON_BODY] } }
conn = Api.build(stubs)
assert_equal 200, conn.get("/items").status
assert_equal 200, conn.get("/items").status
stubs.verify_stubbed_calls
end
def test_the_test_adapter_and_both_middlewares_ship_inside_faraday
# The migration answer, measured: nothing here needs an extra gem.
core = "faraday-#{Faraday::VERSION}"
assert_equal Faraday::Adapter::Test, Faraday::Adapter.lookup_middleware(:test)
assert_equal core, Api.shipping_gem(Faraday::Adapter::Test, :call)
assert_equal core, Api.shipping_gem(Faraday::Response::Json, :on_complete)
assert_equal core, Api.shipping_gem(Faraday::Response::RaiseError, :on_complete)
end
def test_the_default_adapter_is_the_piece_that_moved_out
# net_http is a separate gem faraday depends on — which is why the
# default connection needs no setup and why it is not a stub.
assert_equal :net_http, Faraday.default_adapter
net_http = Faraday::Adapter.lookup_middleware(:net_http)
assert_match(/\Afaraday-net_http-/, Api.shipping_gem(net_http, :call))
end
def test_an_unbundled_adapter_is_simply_not_registered
# The adapters that really did leave core fail at lookup, not at request
# time, so a typo and a missing gem look identical.
err = assert_raises(Faraday::Error) { Faraday::Adapter.lookup_middleware(:typhoeus) }
assert_equal ":typhoeus is not registered on Faraday::Adapter", err.message
end
def test_the_json_middleware_runs_with_no_json_gem_in_the_bundle
# Nothing in the Gemfile provides json — the middleware requires the one
# Ruby ships. That stops being true at faraday 2.12, which adds a runtime
# dependency on the json gem, and json compiles a C extension: on an
# alpine image with no toolchain the install fails there, long before any
# of this runs. This assertion is the tripwire for that upgrade.
refute Gem.loaded_specs.key?("json")
assert defined?(JSON::VERSION)
end
def test_forgetting_the_test_adapter_opens_a_real_socket
# Proof that the stubs are what keeps the suite offline: the same code
# with the default adapter goes to the network. Loopback port 9 is
# closed, so this refuses immediately instead of hanging.
conn = Faraday.new(url: "http://127.0.0.1:9")
assert_raises(Faraday::ConnectionFailed) { conn.get("/items") }
end
end