How to test functions that use sink(type = "message") with testthat

Viewed 60

Within an R package I wrote a function that redirects all output from a sourced script to a log file using

sink(file = "some.log", type = "output")
sink(file = "some.log", type = "message")
source("script.R")

within the function. Now I want to test if this function works as expected which means that I need to test if certain output (including messages) was written to the specified log file.

This works fine when I run the test script in the console. But when I use devtools::test() or R CMD check, the messages are captured somewhere else and don't appear in the log file.

I understand that this behavior is somehow necessary for testthat to work, but how can I test if my function call produced all expected messages?

1 Answers

I think the best option is to leave it up to end-users to call sink() rather than include it as a function in your package. You can provide examples in a vignette to show users how you intend them to use sink() with their scripts.

Edit: you might find this vignette on test fixtures helpful, especially the case study on usethis: https://testthat.r-lib.org/articles/test-fixtures.html#case-study-usethis

Related