How to undo call to `local_dir()` or `local_options()` in global environment?
Closed this issue · 2 comments
Hi,
I am wondering if it is possible to "undo" a call to any withr::local_*()
, like local_dir()
or local_options()
when being run from the global environment (e.g. in a development/debugging scenario) and not from within a function or any well delimited code chunk?
If not, it would be a great feature.
Here is my problem, I am using withr::local_dir()
in a testthat
test to run a test in a local temp directory. Here is a small toy example:
# R/fun.R
my_fun <- function() {
a <- 10
save("a", file = "data.RData") # my function create a dummy file
}
# tests/testthat/test-fun.R
test_that("my_fun", {
test_dir <- withr::local_tempdir()
withr::local_dir(test_dir) # I move to the temp dir to run the test
my_fun()
expect_true(file.exists("data.RData")) # I check that the file is indeed created
})
When I am doing some development/debugging, it may happen that I test my function in "interactive mode", directly running the code chunk within the test in the global environment, e.g. in my example I just run:
test_dir <- withr::local_tempdir()
withr::local_dir(test_dir)
my_fun()
expect_true(file.exists("data.RData"))
instead of running test_that(...)
.
In that case, I am moved to the local temp dir (and same if I use local_options()
, the "local options" are set in the global environment) and I do not know how to undo this except manually (which is not convenient, e.g. if I setup numerous local options) or by exiting my current R session (even less convenient).
Thanks
When you run a local function in the global environment, you should now see something like:
Setting global deferred event(s).
i These will be run:
* Automatically, when the R session ends.
* On demand, if you call `withr::deferred_run()`.
i Use `withr::deferred_clear()` to clear them without executing.
Which tells you what to do :)
Thank you very much!