I'm trying to write a test that my function fails gracefully, with an expected error message (as opposed to failing badly with something incomprehensible). I really should use classed conditions for this, but as a quick hack I thought of using sink
to capture the error message and check that it's what I want:
my_bad_func <- function()
stop("My error message")
test_that("Function fails gracefully",
{
con <- textConnection("errors", open="w")
sink(con, type="message")
expect_error(my_bad_func())
sink(NULL, type="message")
expect_true(any(grepl("My error message", errors)))
})
However, when I run this, it turns out that nothing is captured; the errors
object is empty. I verified that the check above works correctly outside of test_that
.
Is there a way to use sink
with testthat? Or alternatively, is there a better way of writing this test)?