.setup= argument to allow re-usable (but hermetic) local variables?
- Dominant language
- R
- Stars
- 145
- Forks
- 16
- PR merge metrics
- No merged PRs in 30d
Description
In plain {testthat} we can re-use local variables "hermetically" by running some code before expectations:
```r
test_that("a test", {
var1 <- 1
var2 <- 2
expect_equal(var1, var2 - 1)
# ... more tests using var1,var2 ...
})
```
After `"a test"` runs, we don't have to worry about other tests "seeing" `var1`/`var2`, their scope is restricted.
It's not so easy to do this with {patrick}, because we want to declare just once variables used across all the `.cases`. We might also want to declare the `.cases` themselves.
The workaround that I've landed on is to wrap `with_parameters_test_that()` with `local({})`, but this is a tad clumsy and usage of `local({})` is not so prevalent in R code, so it slightly harms readability IMO.
One solution would be to offer a `.setup` argument that encapsulates what `local()` is doing:
```r
with_parameters_test_that(
"a parametrized test",
.setup = {
var1 <- 1
var2 <- 2
cases <- expand.grid(p1 = 1:10, p2 = 10:1)
},
expect_equal(p1 + p2, 10 * var1 + var2 - 1),
.cases = cases
)
```
`.setup` is run first, so `var1` and `var2` are available to `code` _but also_ to the other arguments in the `with_parameters_test_that` call.
WDYT?
Contributor guide
Assessment
This issue has not been assessed yet.