Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use {withr} to create temporary files (that are automatically deleted) in tests #219

Closed
averissimo opened this issue Jan 17, 2024 · 0 comments · Fixed by #220
Closed

Use {withr} to create temporary files (that are automatically deleted) in tests #219

averissimo opened this issue Jan 17, 2024 · 0 comments · Fixed by #220

Comments

@averissimo
Copy link
Collaborator

Simplifies tests by removing manual creation and action to remove on exit.

  • local_file(): for tests defining a specific name
  • local_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"
@averissimo averissimo changed the title Replace manual removal of files with withr::local_file/local_tempfile Use {withr} to create temporary files (that are automatically deleted) in tests Jan 17, 2024
bms63 added a commit that referenced this issue Feb 19, 2024
Closes #219 Uses `{withr}` to create temporary files and graceful handling of Suggests
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
1 participant