GuzzleHttp VCR

This post is over 2 years old and is probably out of date.

A few days ago I pushed out a very small library to help with testing APIs using Guzzle: dshafik/guzzlehttp-vcr.

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 \GuzzleHttp\HandlerStack with either the \Dshafik\GuzzleHttp\VCRHandler middleware, or the GuzzleHttp\Handler\MockHandler 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 Dshafik\GuzzleHttp\VCRHandler::turnOn() passing in the storage location before running the test, and pass in the handler as a guzzle client option:

You can pass in the handler when instantiating the \GuzzleHttp\Client, 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.

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.