Learn R Programming

httptest (version 4.2.2)

with_fake_http: Make all HTTP requests return a fake response

Description

In this context, HTTP verb functions raise a 'message' so that test code can assert that the requests are made. As in without_internet(), the message raised has a well-defined shape, made of three elements, separated by space: (1) the request method (e.g. "GET" or "POST"); (2) the request URL; and (3) the request body, if present. The verb-expectation functions, such as expect_GET and expect_POST, look for this shape.

Usage

with_fake_http(expr)

Value

The result of expr

Arguments

expr

Code to run inside the fake context

Details

Unlike without_internet, the HTTP functions do not error and halt execution, instead returning a response-class object so that code calling the HTTP functions can proceed with its response handling logic and itself be tested. The response it returns echoes back most of the request itself, similar to how some endpoints on http://httpbin.org do.

Examples

Run this code
with_fake_http({
  expect_GET(req1 <- httr::GET("http://example.com"), "http://example.com")
  req1$url
  expect_POST(
    req2 <- httr::POST("http://example.com", body = '{"a":1}'),
    "http://example.com"
  )
  httr::content(req2)
})

Run the code above in your browser using DataLab