Home / Blog / Mock the SellerMagnet API in Ruby Tests Without Spending Credits

Mock the SellerMagnet API in Ruby Tests Without Spending Credits

Test the Ruby/Net::HTTP client that calls the SellerMagnet API without hitting it: reopen Net::HTTP with Module#prepend, run the real seller_magnet.rb unchanged, and cover every billed, free and refunded status code with Minitest, the standard library's own test framework.

November 15, 2026
6 min read
SellerMagnet Team
Share & Bookmark
Terminal window showing a Minitest run that fakes Net::HTTP for the SellerMagnet API while the real Ruby client code runs unchanged

Mock the SellerMagnet API in Ruby tests by faking only Net::HTTP#request (and #started?, the check right before it), never seller_magnet.rb itself: reopen the stdlib Net::HTTP class with Module#prepend so it answers a scripted status, body and headers from a Ruby block, then let SellerMagnet::Client#get, #lookup and .with_retry from the Ruby quickstart run exactly as they would in production. No credit is spent, no socket is opened, and the retry/backoff logic runs for real, just without a real wait.

Key Takeaways

  • Fake Net::HTTP#request, the one stdlib method Client#get calls to reach the network; never fake get() or lookup() themselves.
  • Fake #started?/#start too: Client#get checks started? before every call, and without faking it that line would try to open a real socket before the fake request ever runs.
  • Make the fake fail closed: a request before a test installs its scripted route raises, instead of silently reaching the real, billed API.
  • A 429 is free and worth waiting out for real in production; a 500 is refunded and worth one retry; a 502/503 is billed on every attempt, so with_retry's own attempt cap matters.
  • max_retries = 0 on the real Net::HTTP instance is its own small regression test: Net::HTTP silently re-sends a timed-out GET once by default, and every send is billed.

Why not just call the real API in a Ruby test suite?

Every SellerMagnet API request is billed per the table below, whether it comes from production code or minitest. A CI run that fires on every push would spend credits on every build, a slow or flaky network turns a code bug into a failed pipeline, and a second 500 in a row or a dropped connection cannot be forced on demand against the live API at all. A fake makes every status code, including the rare ones, reproducible on every run.

Scenarios worth testing, and what the fake needs to script for each.
ScenarioChargedRetry?Client should
happy path lookupbillednodecode, 1 credit
"N/A" buy box pricebillednomap to nil, never 0
404 product not foundbillednorecord it, never retry
free gate 400 (invalid marketplaceId)freenofix the request, no retry
401 bad keyfreenostop; never retry
429 concurrency capfreeyeswait Retry-After, then retry
500 internal errorrefundedyes, onceretry once, then stop
502 / 503 upstreambilledyesretry up to attempts = 4
Net::ReadTimeout / Net::OpenTimeoutmay be billedyesretry: the request never got a reply
SocketError (DNS/connection failure)never billedyesretry until attempts exhausted

How do I fake just Net::HTTP, not my own code?

Client#get calls exactly two methods on its Net::HTTP instance: started?/start, then request. Module.new { ... }.prepended onto Net::HTTP intercepts both without touching a single line of the quickstart's own seller_magnet.rb - the same technique WebMock and VCR use under the hood, written here with nothing but the standard library. start sets a flag instead of opening a socket, so use_ssl= (itself gated on started?) still behaves exactly as it does against a real connection, and request calls a scripted route or raises if a test forgot to install one.

Blueprint sequence diagram of a Minitest test faking Net::HTTP#request while the real Ruby client code runs unchanged
Only Net::HTTP#request/#started? are faked; Client#get and .with_retry run unmodified.

fake_transport.rb - reopens Net::HTTP, fails closed on a missing route

# fake_transport.rb - fakes only Net::HTTP#request and #started?, the exact pair
# SellerMagnet::Client#get calls ("@http.start unless @http.started?" then
# "@http.request(request)"). seller_magnet.rb is required completely unmodified;
# this file only re-opens the STDLIB Net::HTTP class, the same technique WebMock
# and VCR use to intercept Ruby HTTP clients in tests. Fails closed: a request
# before a test installs a route raises instead of silently reaching the real API.
require "net/http"

module FakeTransport
  @mutex = Mutex.new
  @route = nil
  @calls = []

  class << self
    def install(route)
      @mutex.synchronize do
        @route = route
        @calls = []
      end
    end

    def reset
      @mutex.synchronize do
        @route = nil
        @calls = []
      end
    end

    def calls
      @mutex.synchronize { @calls.dup }
    end

    def record(request)
      @mutex.synchronize { @calls << request }
    end

    def current_route
      @mutex.synchronize { @route }
    end
  end
end

# Duck-types only what SellerMagnet::Client#get reads off a Net::HTTPResponse:
# .code (a String), .body and []("Retry-After").
FakeResponse = Struct.new(:code, :body, :headers) do
  def initialize(code:, body:, headers: {})
    super(code.to_s, body, headers)
  end

  def [](key)
    headers.find { |k, _| k.to_s.casecmp?(key.to_s) }&.last
  end
end

module Net
  class HTTP
    prepend(Module.new do
      # Pretend .start opened a connection without ever touching a real
      # socket. started? stays false (the real default) until .start runs,
      # exactly like the real Net::HTTP, so use_ssl= (which itself checks
      # started?) still behaves exactly as it does in production code.
      def start
        @fake_started = true
        self
      end

      def started?
        @fake_started ||= false
      end

      def request(req, body = nil, &block)
        FakeTransport.record(req)
        route = FakeTransport.current_route
        unless route
          raise "FakeTransport: install(route) first - no request may reach the real API"
        end
        route.call(req)
      end
    end)
  end
end
Blueprint table of test scenarios against the SellerMagnet API's status codes, billing and the correct Ruby client reaction
Each row needs its own scripted response; a happy-path test alone misses most of this.

What does a full Minitest scenario suite look like?

Each test installs its own scripted route and FakeTransport.reset runs again in teardown, so a forgotten setup in the next test cannot inherit a leftover route. Kernel#sleep is stubbed for the whole suite so with_retry's real exponential backoff still executes and is still asserted on (the 429 test checks the recorded wait honoured Retry-After: 2), just without the real delay. A dedicated concurrency test drives 5 threads against the fake, mirroring the quickstart's own bulk.rb worker count, to prove the fake's mutex-guarded call log is thread-safe under the same load the real client relies on.

client_test.rb - the scenario suite, run for real below

require "minitest/autorun"
require "net/http"
require_relative "fake_transport"
require_relative "seller_magnet"

# Stub Kernel#sleep for the whole suite: with_retry's own exponential backoff
# (2**attempt + jitter, capped implicitly by ATTEMPTS) still runs and is still
# asserted on below, it just does not really wait. Production code is never
# affected: this file is only loaded by the test runner.
module SleepStub
  @waits = []
  class << self
    attr_reader :waits

    def reset
      @waits = []
    end
  end

  def sleep(seconds)
    SleepStub.waits << seconds
    0
  end
end
Object.prepend(SleepStub)

ENV["SELLERMAGNET_API_KEY"] ||= "test-key"
ASIN = "B0CL61F39H"
MARKET = "ATVPDKIKX0DER"

def ok(data)
  FakeResponse.new(code: 200, body: JSON.generate({ "success" => true, "data" => data }))
end

def fail_response(status, message, headers: {})
  FakeResponse.new(code: status, body: JSON.generate({ "success" => false, "message" => message }), headers: headers)
end

def product(price)
  { "productInfo" => { "asin" => ASIN, "title" => "PlayStation5 console (slim)",
                        "buyBoxInfo" => { "price" => price, "currencyCode" => "USD" },
                        "link" => "https://www.amazon.com/dp/#{ASIN}" } }
end

class ClientTest < Minitest::Test
  def setup
    FakeTransport.reset
    SleepStub.reset
    @client = SellerMagnet::Client.new("test-key")
  end

  def teardown
    FakeTransport.reset
  end

  def test_max_retries_is_zero_so_nethttp_never_silently_resends
    http = @client.instance_variable_get(:@http)
    assert_equal 0, http.max_retries
  end

  def test_happy_path_lookup
    FakeTransport.install(->(_req) { ok(product(444.99)) })
    row = @client.lookup(ASIN, MARKET)
    assert_equal 444.99, row[:price]
    assert_equal "USD", row[:currency]
    assert_equal 1, FakeTransport.calls.size
  end

  def test_no_featured_offer_price_is_nil_not_zero
    FakeTransport.install(->(_req) { ok(product("N/A")) })
    row = @client.lookup(ASIN, MARKET)
    assert_nil row[:price]
    assert_equal "USD", row[:currency]
  end

  def test_404_is_billed_once_and_never_retried
    FakeTransport.install(->(_req) { fail_response(404, "Product not found") })
    error = assert_raises(SellerMagnet::ApiError) { SellerMagnet.with_retry { @client.lookup(ASIN, MARKET) } }
    assert_equal 404, error.status
    assert_equal 1, FakeTransport.calls.size
  end

  def test_free_gate_400_sends_no_retry_after
    FakeTransport.install(->(_req) { fail_response(400, "Missing required parameter(s): marketplaceId") })
    error = assert_raises(SellerMagnet::ApiError) { @client.get("amazon-product-lookup", asin: ASIN) }
    assert_equal 400, error.status
    assert_equal 0.0, error.retry_after
  end

  def test_401_stops_without_retrying
    FakeTransport.install(->(_req) { fail_response(401, "Invalid or inactive API key.") })
    error = assert_raises(SellerMagnet::ApiError) { SellerMagnet.with_retry { @client.lookup(ASIN, MARKET) } }
    assert_equal 401, error.status
    assert_equal 1, FakeTransport.calls.size
  end

  def test_429_is_free_and_retried_honouring_retry_after
    calls = 0
    FakeTransport.install(->(_req) {
      calls += 1
      calls == 1 ? fail_response(429, "Max 5 concurrent requests per API key. Retry shortly.",
                                  headers: { "Retry-After" => "2" }) : ok(product(444.99))
    })
    row = SellerMagnet.with_retry { @client.lookup(ASIN, MARKET) }
    assert_equal 444.99, row[:price]
    assert_equal 2, FakeTransport.calls.size
    assert_operator SleepStub.waits.first, :>=, 2.0
  end

  def test_500_without_extra_retry_after_is_retried_once
    calls = 0
    FakeTransport.install(->(_req) {
      calls += 1
      calls == 1 ? fail_response(500, "Internal error") : ok(product(444.99))
    })
    row = SellerMagnet.with_retry { @client.lookup(ASIN, MARKET) }
    assert_equal 444.99, row[:price]
    assert_equal 2, FakeTransport.calls.size
  end

  def test_second_500_in_a_row_is_reported_not_looped
    FakeTransport.install(->(_req) { fail_response(500, "Internal error") })
    error = assert_raises(SellerMagnet::ApiError) { SellerMagnet.with_retry { @client.lookup(ASIN, MARKET) } }
    assert_equal 500, error.status
    assert_equal 2, FakeTransport.calls.size
  end

  def test_502_is_retried_up_to_the_attempt_cap
    FakeTransport.install(->(_req) { fail_response(502, "Upstream error") })
    error = assert_raises(SellerMagnet::ApiError) { SellerMagnet.with_retry { @client.lookup(ASIN, MARKET) } }
    assert_equal 502, error.status
    assert_equal 4, FakeTransport.calls.size
  end

  def test_network_read_timeout_is_retried_by_with_retry
    calls = 0
    FakeTransport.install(->(_req) {
      calls += 1
      raise Net::ReadTimeout, "timed out" if calls == 1

      ok(product(444.99))
    })
    row = SellerMagnet.with_retry { @client.lookup(ASIN, MARKET) }
    assert_equal 444.99, row[:price]
    assert_equal 2, FakeTransport.calls.size
  end

  def test_socket_error_exhausts_attempts_and_raises
    FakeTransport.install(->(_req) { raise SocketError, "getaddrinfo: Name or service not known" })
    assert_raises(SocketError) { SellerMagnet.with_retry { @client.lookup(ASIN, MARKET) } }
    assert_equal 4, FakeTransport.calls.size
  end

  def test_fake_transport_fails_closed_without_install
    error = assert_raises(RuntimeError) { @client.get("amazon-product-lookup", asin: ASIN, marketplaceId: MARKET) }
    assert_match(/install\(route\) first/, error.message)
  end
end

class ConcurrencyTest < Minitest::Test
  def setup
    FakeTransport.reset
  end

  def teardown
    FakeTransport.reset
  end

  def test_five_threads_share_the_fake_transport_safely
    FakeTransport.install(->(_req) { ok(product(444.99)) })
    rows = Queue.new
    workers = Array.new(5) do
      Thread.new do
        client = SellerMagnet::Client.new("test-key") # one connection per thread, as bulk.rb does
        rows << client.lookup(ASIN, MARKET)
      end
    end
    workers.each(&:join)
    assert_equal 5, FakeTransport.calls.size
    assert_equal 5, rows.size
    5.times { assert_equal 444.99, rows.pop[:price] }
  end
end

ruby client_test.rb --verbose output (unmodified run)

Run options: --verbose --seed 1423

# Running:

ClientTest#test_second_500_in_a_row_is_reported_not_looped = 0.00 s = .
ClientTest#test_happy_path_lookup = 0.00 s = .
ClientTest#test_no_featured_offer_price_is_nil_not_zero = 0.00 s = .
ClientTest#test_404_is_billed_once_and_never_retried = 0.00 s = .
ClientTest#test_max_retries_is_zero_so_nethttp_never_silently_resends = 0.00 s = .
ClientTest#test_502_is_retried_up_to_the_attempt_cap = 0.00 s = .
ClientTest#test_free_gate_400_sends_no_retry_after = 0.00 s = .
ClientTest#test_500_without_extra_retry_after_is_retried_once = 0.00 s = .
ClientTest#test_401_stops_without_retrying = 0.00 s = .
ClientTest#test_fake_transport_fails_closed_without_install = 0.00 s = .
ClientTest#test_network_read_timeout_is_retried_by_with_retry = 0.00 s = .
ClientTest#test_429_is_free_and_retried_honouring_retry_after = 0.00 s = .
ClientTest#test_socket_error_exhausts_attempts_and_raises = 0.00 s = .
ConcurrencyTest#test_five_threads_share_the_fake_transport_safely = 0.01 s = .

Finished in 0.035931s, 389.6388 runs/s, 1113.2537 assertions/s.

14 runs, 40 assertions, 0 failures, 0 errors, 0 skips

Never hand-write a fake of get() or lookup() itself

A fake that reimplements Client#get or #lookup tests the fake's own logic, not the real client. Fake the stdlib HTTP class one layer below your code, so a real bug in the parsing or retry logic still shows up as a failing test.

Does the same pattern work for other languages?

Yes, fake the one thing the real code talks to over the network, whatever shape that takes. The Python guide fakes requests.Session.get, the Go guide fakes http.RoundTripper, and the Node/Jest guide fakes globalThis.fetch; this guide reopens Net::HTTP itself with Module#prepend, because that is the one stdlib seam every Net::HTTP-based Ruby client, including this quickstart's, already calls through. The 429/Retry-After guide and the 502/503 retry guide are the production behaviour this suite checks against; keep all three in sync when the retry logic changes. Credit costs and the free trial are on the pricing page, and every endpoint's parameters are in the API documentation and code examples.

Frequently Asked Questions

Can a Ruby test suite call the real SellerMagnet API instead of faking it?

It can, but every call is billed the same as production traffic, a CI run that fires on every push then spends credits on every build, and a 404, a 429-then-success or a dropped connection is hard to force on demand against the live API. A fake makes every status code, including the rare ones, reproducible on every run for zero credits.

Why monkey-patch Net::HTTP instead of changing seller_magnet.rb?

Because faking one layer below your own code is what actually tests it: a fake that reimplements Client#get or #lookup would test the fake's logic, not the real client. Net::HTTP#request is the one stdlib method Client#get calls to reach the network, the same idea as faking http.RoundTripper in Go or requests.Session.get in Python, and it is the same technique WebMock and VCR use to intercept Ruby HTTP clients, just written here with nothing but the standard library (Module#prepend), so seller_magnet.rb itself needs no change at all.

Why override Net::HTTP#started? too, not just #request?

Client#get calls @http.start unless @http.started? before every request. Without faking started? as well, that line would try to open a real TCP/TLS connection to sellermagnet-api.com before the fake request method ever runs. The fake tracks its own @fake_started flag instead, so use_ssl= (which itself checks started?) still behaves exactly as it does with a real connection, and no socket is ever opened.

Does this suite prove Net::HTTP's own hidden retry is really off?

Indirectly: max_retries = 0 is asserted directly as a configuration test, since Net::HTTP would otherwise silently re-send a timed-out idempotent GET once on its own, which the fake cannot observe from outside (it replaces #request before that internal logic runs). The configuration test pins the setting itself, so a future edit that drops max_retries = 0 fails this test immediately instead of silently reappearing.

Does the same pattern work for other languages?

Yes, fake the one call the real code makes to reach the network, whatever shape that takes. The Python guide fakes requests.Session.get, the Go guide fakes http.RoundTripper, and the Node/Jest guide fakes globalThis.fetch. This guide reopens Net::HTTP itself with prepend, one stdlib class method below Client#get.

Bottom line: reopen Net::HTTP with Module#prepend (or your language's equivalent one layer below the HTTP call), run the real client code against scripted responses for every billed, free and refunded status, and make the fake fail closed so a forgotten setup cannot send a real, billed request. The whole suite above runs in well under a tenth of a second and spends zero credits.

Ready to Extract Amazon Data at Scale?

Start building with SellerMagnet API today. Real-time product data, competitive pricing, and review analytics at your fingertips.

150 free API credits • No credit card required • Cancel anytime