In my understanding, anything put inside test_that()
should be compartmentalized, meaning that if I load a package in test_that()
, its functions and methods shouldn't be available in other test_that()
calls.
In the example below, there are 3 (empty) tests:
- In the first one, we can see that the method
as.matrix.get_predicted
is not available in the namespace. - In the second one, I load the package
insight
, which provides the methodas.matrix.get_predicted
. In my understanding, this method should only be available in thistest_that()
call. - In the third one, we can see that the method is available.
library(testthat)
test_that("foo 1", {
print("as.matrix.get_predicted" %in% methods(as.matrix))
})
#> [1] FALSE
#> ── Skip (???): foo 1 ───────────────────────────────────────────────────────────
#> Reason: empty test
test_that("foo 2", {
invisible(insight::get_parameters)
})
#> ── Skip (???): foo 2 ───────────────────────────────────────────────────────────
#> Reason: empty test
test_that("foo 3", {
print("as.matrix.get_predicted" %in% methods(as.matrix))
})
#> [1] TRUE
#> ── Skip (???): foo 3 ───────────────────────────────────────────────────────────
#> Reason: empty test
Why is that? Are there some workarounds?
Edit: I'm looking for a solution specific to testthat
, not another testing framework.
library()
has global side effects, You'd have to explicitly unload the packages/namespaces yourself. Probably best dealt with via a test fixture: testthat.r-lib.org/articles/test-fixtures.html – Milanwithr
haswith_package()
andlocal_package()
but they don't unload the package namespace so I don't really understand their purpose – Rutandetach("package:parameters", unload = TRUE)
, but that won't unregister S3 methods or unload the dependencies of parameters that are loaded automatically bylibrary(parameters)
. The correct approach is to run the relevant tests in a new R process, perhaps by having more than one*.R
file undertests/
(what people who spurn testthat do). – Uraliteparameters
in another test file (and if this test file is ran before the others), the S3 method will still be available in other test files so that doesn't work. – Rutan