Consider the following function that's meant to be ran in an R subprocess:
foo <- function() stop("foo error")
I'd like to capture the error message in a snapshot test.
testthat::test_that("foo", {
testthat::expect_snapshot(callr::r(foo), error = TRUE)
})
The above will produce the following snapshot, usually with all the backtrace in more complex cases which makes the snapshot quite messy:
# foo
Code
callr::r(foo)
Condition
Error:
! in callr subprocess.
Caused by error:
! foo error
I'm trying to simplify the snapshot to only print the error thrown by foo()
. This is what I ideally want:
Code
executed code
Output
<simpleError: foo error.>
I've tried to capture the error in a stderr
file or tryCatch()
but the best I could get was to remove the backtrace only:
err <- callr::r(foo, stderr = withr::local_tempfile())
err$stderr
tmp <- withr::local_tempfile()
callr::r(foo, stderr = tmp)
readLines(tmp)
tryCatch(callr::r(foo), error = function(e) e)
How could I only output the foo error
only?
Also, is there a way to use callr::r()
inside expect_error()
? I usually like to structure error snapshots as follows when testing for multiple errors:
test_that("blah", {
expect_snapshot({
(expect_error(
expr_1
))
(expect_error(
expr_2
))
(expect_error(
expr_n
))
})
})
But I couldn't make it work at all with callr::r()
. I have to create a specific snapshot for each error.