Think about a state of affairs: your software depends on an exterior service chargeable for card costs. The service has a tiny API: get the cardboard quantity (masks) by person ID, cost X
{dollars} from the person. How can we check the code that works with this API?
After all, you’ll be able to really request that exterior service within the assessments. Possibly it even has a sandbox for such instances. However this answer just isn’t so environment friendly. To begin with, it slows down the assessments: each request has a time price. Secondly, it makes assessments flaky: community points will trigger them to randomly fail. Thirdly, it is not all the time doable: the exterior service could don’t have any sandbox or have strict request limits.
In such instances, it’s higher to make use of stubs for exterior companies. I exploit 4 choices of stubs, relying on the exterior service: is it my very own or another person’s, secure or incessantly altering?
One of many choices is a pretend service on Sinatra. Equivalent to this one:
let(:fake_api) do
Class.new Sinatra::Base do
get "/customers/:user_id/card" do
content_type :json
{ quantity: "4111...1111" }.to_json
finish
finish
finish
earlier than do
stub_request(:any, /api.nanocashier.com/).to_rack(fake_api)
finish
There are two fascinating issues within the above code. Firstly, Class.new
with the Sinatra::Base
guardian in let
, so you do not add a worldwide fixed from the check. Secondly, the stub_request
of Webmock, which routes all requests to the rack software.
I exploit such rack-based stubs when I’ve to mock an exterior service which does not have its personal stubs (e.g. stripe-ruby-mock) and making adapter-like stub just isn’t doable.