Reputation: 117
Using RSpec's mock/stub, how do I write a unit test for the find_by_id
method?
I want to use RSpec, not WebMock or VCR. How do I create a stub for the request/response?
class RapidApiClient
HOST_URL = 'https://brianiswu-open-brewery-db-v1.p.rapidapi.com/breweries'
API_KEY = 'private_api_key'
def request_api(url)
Excon.get(
url,
headers: {
'X-RapidAPI-Host' => HOST_URL,
'X-RapidAPI-Key' => 'API_KEY'
}
)
end
def find_by_id(id)
response = request_api("#{HOST_URL}/#{id}")
return nil if response.status != 200
JSON.parse(response.body)
end
end
The response is:
[
{"id":4 , "name":"Ban Brewing Company" , "brewery_type":"micro", "city":"Tulsa" , "state":"OK"}
{"id":44,"name":"Tab Brewing" "brewery_type":"micro", "city":"Birmingham", "state":"MO"}
]
Upvotes: 2
Views: 5422
Reputation: 4378
You can stub the request_api
method itself so that you don't have to make the HTTP request using something like this:
expect_any_instance_of(RapidApiClient)
.to receive(:request_api)
.and_return([
{"id":4 , "name":"Ban Brewing Company" , "brewery_type":"micro", "city":"Tulsa" , "state":"OK"}
{"id":44,"name":"Tab Brewing" "brewery_type":"micro", "city":"Birmingham", "state":"MO"}
])
if you want to stub the actaul request/response.
You can sub the get
method of Excon
library like this:
expect(Excon)
.to receive(:get)
.and_return(Excon::Response.new(
:status => 200,
:body => '[{"id":4 , "name":"Ban Brewing Company","brewery_type":"micro", "city":"Tulsa" , "state":"OK"},{"id":44,"name":"Tab Brewing" "brewery_type":"micro", "city":"Birmingham", "state":"MO"}]'
))
Upvotes: 5