简体   繁体   中英

How to run code after test failure with testthat?

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"))
})

You could use on.exit :

## test-foo_files.R

## Setup
temp <- tempdir()
## Triggered cleaning
on.exit(unlink(temp))

file.create("file1.R")
file.create("file2.R")

## test
test_that("List all R files works", {
  expect_equal(list_R_scripts("temp"), c("file1.R", "file2.R"))
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM