Use `{withr}` to create temporary files (that are automatically deleted) in tests
averissimo opened this issue · comments
Simplifies tests by removing manual creation and action to remove on exit.
local_file()
: for tests defining a specific namelocal_tempfile()
: when creating generic temporary file without any name requirement
Example:
diff --git a/tests/testthat/test-write.R b/tests/testthat/test-write.R
index d53c7eb..d3b1e99 100644
--- a/tests/testthat/test-write.R
+++ b/tests/testthat/test-write.R
@@ -1,20 +1,14 @@
data_to_save <- dplyr::tibble(X = c(1, 2, NA), Y = c("a", "", "c"), Z = c(1, 2, 3))
test_that("xportr_write: exported data can be saved to a file", {
- tmpdir <- tempdir()
- tmp <- file.path(tmpdir, "xyz.xpt")
-
- on.exit(unlink(tmpdir))
+ tmp <- local_file("xyz.xpt")
xportr_write(data_to_save, path = tmp)
expect_equal(read_xpt(tmp), data_to_save)
})
@@ -64,15 +52,10 @@ test_that("xportr_write: exported data can be saved to a file with a existing me
})
test_that("xportr_write: expect error when invalid multibyte string is passed in label", {
- tmpdir <- tempdir()
- tmp <- file.path(tmpdir, "xyz.xpt")
-
- on.exit(unlink(tmpdir))
-
expect_error(
xportr_write(
data_to_save,
- tmp,
+ local_file("xyz.xpt"),
metadata = data.frame(
dataset = "data_to_save",
label = "Lorizzle ipsizzle dolizzl\xe7 pizzle"