I'm developing a package in which I set several options using .onLoad, and I want to write tests for the behavior. I believe I would most likely need to do this in a new R subprocess using callr::r(), but I'm not sure exactly how. E.g.
Set-up testing, located at tests/testthat/test-zzz.R
test_that("test .onLoad", {
callr::r(function() {
loadNamespace("mypkg")
# and here I would write checks that the options set with .onLoad() have actually worked
})
})
However, the attempt to use loadNamespace() (or library()) results in the error that "there is no package called ‘mypkg’". What would be the proper way to reference an in-development package in its own tests like this?
You can probably do this with callr::r(), at least I remember doing similar things in the past. One catch is that you need to load the package in the subprocess differently in R CMD check and in devtools::test() (and testthat::test_local() etc.).
In R CMD check the package is installed and it is on the library path, so you should be able to load it normally.
Otherwise you'd load it with load_all(). Something like this may work, within test_that():
The ... part would return whatever information you need to test that .onLoad() worked properly. (You can't run testthat::expect_*() in the callr subprocess, the testing happens in the main process.
It would probably make sense to skip_on_cran() this test, because it is easy to miss some platform dependent detail that might cause it to fail on CRAN, even if it is OK on your local testing.
Instead of the testthat internal functions, you can use pkgload::is_dev_package() to decide if your package was loaded with load_all(), in which case you would use load_all() in the subprocess as well:
There might be a more eloquent way around the issue, but I had found an explicit call to .onLoad() was needed to get {covr} to detect that the function was actually being tested and for the tests to be counted towards the code coverage.