Learn R Programming

httptest (version 3.0.0)

capture_requests: Record API responses as mock files

Description

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, simplify = TRUE, verbose = FALSE, redact)

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.

...

Arguments passed through capture_requests to start_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 when simplify is FALSE, the "response" object will be written out to a .R file using base::dput().

verbose

logical: if TRUE, a message is printed for every file that is written when capturing requests containing the absolute path of the file. Useful for debugging if you're capturing but don't see the fixture files being written in the expected location. Default is FALSE.

redact

function to run to purge sensitive strings from the recorded response objects. This argument is deprecated: use set_redactor() or a package redactor instead. See vignette("redacting") for more details.

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.

Mocks stored by this context are written out as plain-text files, either with extension .json if the request returned JSON content or with extension .R otherwise. The .R files contain syntax that when executed recreates the httr "response" object. 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.

Examples

Run this code
# NOT RUN {
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()
# }

Run the code above in your browser using DataLab