capture_requests
is a context that collects the responses from requests
you make and stores them as mock files. This enables you to perform a series
of requests against a live server once and then build your test suite using
those mocks, running your tests in with_mock_api()
.
Usage
capture_requests(expr, path, ...)
start_capturing(path = NULL, simplify = TRUE)
stop_capturing()
Arguments
- expr
Code to run inside the context
- path
Where to save the mock files. Default is the first directory in
.mockPaths()
, which if not otherwise specified is the current working directory. It is generally better to call.mockPaths()
directly if you want to write to a different path, rather than using thepath
argument.- ...
Arguments passed through
capture_requests
tostart_capturing
- simplify
logical: if
TRUE
(default), JSON responses with status 200 will be written as just the text of the response body. In all other cases, and whensimplify
isFALSE
, the "response" object will be written out to a .R file usingbase::dput()
.
Value
capture_requests
returns the result of expr
. start_capturing
invisibly returns the path
it is given. stop_capturing
returns nothing;
it is called for its side effects.
Details
start_capturing
and stop_capturing
allow you to turn on/off request
recording for more convenient use in an interactive session.
Recorded responses are written out as plain-text files. By storing fixtures as plain-text files, you can more easily confirm that your mocks look correct, and you can more easily maintain them without having to re-record them. If the API changes subtly, such as when adding an additional attribute to an object, you can just touch up the mocks.
If the response has status 200 OK
and the Content-Type
maps to a supported file extension---currently .json
,
.html
, .xml
, .txt
, .csv
, and .tsv
---just the response body will be
written out, using the appropriate extension. 204 No Content
status
responses will be stored as an empty file with extension .204
. Otherwise,
the response will be written as a .R
file containing syntax that, when
executed, recreates the
httr
"response" object.
If you have trouble when recording responses, or are unsure where the files
are being written, set options(httptest.verbose=TRUE)
to print a message
for every file that is written containing the absolute path of the file.
See also
build_mock_url()
for how requests are translated to file paths.
And see vignette("redacting")
for details on how to prune sensitive
content from responses when recording.
Examples
if (FALSE) {
capture_requests({
GET("http://httpbin.org/get")
GET("http://httpbin.org")
GET("http://httpbin.org/response-headers",
query = list(`Content-Type` = "application/json")
)
})
# Or:
start_capturing()
GET("http://httpbin.org/get")
GET("http://httpbin.org")
GET("http://httpbin.org/response-headers",
query = list(`Content-Type` = "application/json")
)
stop_capturing()
}