How can I set an option in testthat before my package is loaded?

Viewed 24

I am writing unit tests for a package using testthat.

The package maintains a cache of database connections, which are configured with YAML files. The cache is populated during loading by searching for config files in specific paths, including rappdirs::site_config_dir() and rappdirs::user_config_dir().

This behaviour is desired in normal usage but during testing it means the tests will not be reproducible on different machines and over time.

My current approach is to create a configure/don't configure switch based on a global option in .onLoad():

    no_connect <- options("SQLHELPER_NO_CONNECT_ON_LOAD")

    if(is.null(no_connect[[1]])){
      create_connections()

    } else if(no_connect[[1]] == FALSE) { 
      create_connections()
    }

which works interactively; my question is:

How can I make testthat set the option before it loads the package?

(I have tried fiddling with tests/testthat.R, but it is not recommended and only used in R CMD check anyway. I'm hoping for something that also works with testthat::test() etc)

UPDATE I thought briefly that I could set the option in tests/testthat/setup.R, but I think I must have got confused after playing with setting and unsetting it for an afternoon. For anyone reading this in search of an answer, setup.R is run by testthat after .onLoad()is run by loading the package.

0 Answers
Related