Using sink() with testthat

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)?

Ugh, it was as simple as providing the error message to expect_error:

test_that("Function fails gracefully",
{
    expect_error(my_bad_func(), "My error message")
})
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.