How to use `withr::defer()` instead of `testthat::setup()` in R?

Viewed 58

I would like to understand what are the current alternatives to setup() and teardown() in testthat 3rd edition. I found this blog post where it is discussed that setup() and teardown() are deprecated in favour of test fixures.

I checked that post and another recommended one (i.e., this one), and the recommendation is to use withr::defer(). However, I don't fully get it.

Suppose I two simple tests. Each test relies on getting some external resources, then performs a check.

# First test.
test_that("..." {
    # Super long process to get this data.
    data <- matrix(rnorm(9), 3, 3)

    # My test.
    expect_equal(nrow(data), 3)
})

# Second test.
test_that("..." {
    # Super long process to get this data.
    data <- matrix(rnorm(9), 3, 3)

    # My test.
    expect_equal(ncol(data), 3)
})

Normally, I would use setup() to perform the intensive process that generates the data object and ensure that this object is available for all tests in that file. Something like this:

setup({
    # Super long process to get this data.
    data <- matrix(rnorm(9), 3, 3)
})

Then, I would carry on with my tests.

# First test.
test_that("..." {
    expect_equal(nrow(data), 3)
})

# Second test.
test_that("..." {
    expect_equal(ncol(data), 3)
})

For the sake of this question, let's assume that I can't squash the two tests together. How can I use withr::defer() to achieve the same behavior as setup() above?

0 Answers
Related