-
Notifications
You must be signed in to change notification settings - Fork 6
Stub Responses
Matt Muller edited this page Apr 12, 2024
·
5 revisions
Stubbed responses are a feature that allows for mocking responses during testing. Mocked responses do not use the network.
To enable the stub responses feature, the :stub_responses
configuration on the Client must be set to true. By enabling this feature, no network calls are made.
Stubs are registered through the stub_responses
method on the Client instance. The stub_responses
method takes the operation to stub as its first argument, and any sequential arguments are stubs for that operation. Sequential stubs defined in this way are ordered and are "consumed" until the last stub which is repeated indefinitely. Any of the following can be registered as a stub:
- Exception or ApiError - raised as is.
- Hash - must contain a
:data
or:error
key containing another hash.- Data hash is parsed into an output Type.
- Errors hash must provide a
:class
to raise and optionally any:data
for the error.
- nil - uses the default stub.
-
Hearth::Structure
- used as is. -
Hearth::Response
- replaces the Response that would be returned. - Proc - must return any one of the above options. Procs take the input Type as an argument. This is useful for dynamic stubbing based upon input.
client = HighScoreService::Client.new(stub_responses: true)
# => #<HighScoreService::Client ... >
# Stub 3 sequential calls
client.stub_responses(
:create_high_score,
# Stub modeled data
{ data: { high_score: { game: 'fake game', score: -1 } } },
# Stub modeled error
{ error: { class: HighScoreService::Errors::UnprocessableEntityError, data: { errors: { "game" => ['is a bad game!'] } } } },
# Stub instance of error (NetworkingError)
Hearth::NetworkingError.new(Timeout::Error.new('service is dead'))
)
# => [{:data=>{:high_score=>{:game=>"fake game", :score=>-1}}},
# {:error=>{:class=>HighScoreService::Errors::UnprocessableEntityError, :data=>{:errors=>{"game"=>["is a bad game!"]}}}},
# #<Hearth::NetworkingError: Encountered an error while transmitting the request: service is dead>]
client.create_high_score(high_score: {})
# => #<Hearth::Output @data= ... game="fake game", score=-1 >
client.create_high_score(high_score: {})
# raises UnprocessableEntityError, {:errors=>{"game"=>["is a bad game!"]}}
client.create_high_score(high_score: {})
# raises Hearth::NetworkingError, service is dead