A few days ago I pushed out a very small library to help with testing APIs using Guzzle: dshafik/guzzlehttp-vcr.
Here, Guzzle VCR (or dshafik/guzzlehttp-vcr): https://t.co/n2KDQ5dKPy — hopefully it's useful
/cc @mtdowling
— Davey Shafik (@dshafik) August 21, 2015
This is a simple middleware that records a request’s response the first time it’s made in a test, and then replays it in response to requests in subsequent runs.
It does this by returning a Guzzle GuzzleHttpHandlerStack
with either the DshafikGuzzleHttpVCRHandler
middleware, or the GuzzleHttpHandlerMockHandler
added. The first will record the responses to JSON files, while the latter will be pre-loaded with those responses and will return them when requests are made.
It’s important to understand that the responses are returned in order regardless of whether it is the same request being made.
The purpose of this library is to just make it easier to create and update your tests for API clients.
Usage is simple, just call DshafikGuzzleHttpVCRHandler::turnOn()
passing in the storage location before running the test, and pass in the handler as a guzzle client option:
View this code snippet on GitHub.
You can pass in the handler when instantiating the GuzzleHttpClient
, or when making the individual requests — if you use the same instance for the individual requests it will re-use the same JSON file for storage, otherwise if you pass in unique instances (with unique storage files) it will create individual ones. I recommend passing in the handler to the constructor, but ensuring that you use a new instance (of the middleware, and the client) for each test.
View this code snippet on GitHub.
Hopefully folks find this useful, do let me know if you do. If you have issues, please report them and pull requests are welcome!
I’ll be releasing a new Akamai library which uses dshafik/guzzlehttp-vcr next week (probably) so look out for that if you want to see it’s use in a real project.
Source: Davey Shaifk