This is my test file:
## test-foo_files.R
## Setup
dir.create("temp")
file.create("temp/file1.R")
file.create("temp/file2.R")
## test
test_that("List all R files works", {
expect_equal(list_R_scripts("temp"), c("file1.R", "file2.R"))
})
## Cleaning
unlink("temp")
How to make the cleaning part running even if the test fails?
The answer from @Waldi is correct but thanks to him I have found a cleaner way to do it after some research.
It is called fixtures
(see here) and works with the package withr
.
withr::defer()
solves some drawbacks of the on.exit()
function.
One clean design to organize all that, is to use setup-xxx.R
files like that:
## tests/testthat/setup-dir-with-2-files.R
fs::dir_create("temp")
fs::file.create(paste0("temp/", c("file1.R", "file2.R"))
withr::defer(fs::dir_delete("temp"), teardown_env())
And the test file is now:
## tests/testthat/test_list_r_scripts.R
test_that("List all R files works", {
expect_equal(list_R_scripts("temp"), c("file1.R", "file2.R"))
})