You can use testthat's setup files. You start the app in a setup file and also register a teardown expression for it. local_app_process() can do both in one go. Your tests/testthat/setup-http.R may look like this:

#| eval: false
http <- webfakes::local_app_process(
  webfakes::httpbin_app(),
  .local_envir = testthat::teardown_env()
)
#| include: false
http <- webfakes::new_app_process(webfakes::httpbin_app())

(Before testthat 3.0.0, you had to write the teardown expression in a tests/testthat/teardown-http.R file. That still works, but a single setup file is considered to be better practice, see this testthat vignette.)

In the test cases you can query the http app process to get the URLs you need to connect to:

#| include: false
library(testthat)
test_that("fails on 404", {
  url <- http$url("/status/404")
  response <- httr::GET(url)
  expect_error(
    httr::stop_for_status(response),
    class = "http_404"
  )
})
#| include: false
http$stop()

When writing your tests interactively, you may create a http app process in the global environment, for convenience. You can source() your setup-http.R file for this. Alternatively, you can start the app process in a helper file. See "How do I start the app when writing the tests?" just below.



gaborcsardi/pressr documentation built on June 2, 2025, 2:10 a.m.