Consider a dummy a package foo
that's intended to be used in Quarto or R Markdown. The package contains the following R script:
.onLoad <- function() print(rmarkdown::metadata$title)
I'd like to test that feature:
# helpers
local_stuff <- function(title, env = parent.frame()) {
temp_dir <- withr::local_tempdir(.local_envir = env)
temp_file <- withr::local_tempfile(
lines = glue::glue("
---
title: {title}
---
```{{r test}}
library(foo)
```
"),
fileext = ".Rmd",
tmpdir = temp_dir,
.local_envir = env
)
rmarkdown::render(temp_file, clean = FALSE, quiet = TRUE)
temp_dir
}
read_local_md <- function(dir) {
file <- list.files(dir, pattern = "\\.md$", full.names = TRUE)
cat(readr::read_file(file))
}
testthat::test_that("", {
testthat::local_edition(3)
dir <- local_stuff("bar")
testthat::expect_snapshot(read_local_md(dir))
dir <- local_stuff("baz")
testthat::expect_snapshot(read_local_md(dir))
})
#> Can't compare snapshot to reference when testing interactively.
#> ā¹ Run `devtools::test()` or `testthat::test_file()` to see changes.
#> Current value:
#> Code
#> read_local_md(dir)
#> Output
#> ---
#> title: bar
#> ---
#>
#> ```r
#> library(foo)
#> #> [1] "bar"
#> ```
#> Can't compare snapshot to reference when testing interactively.
#> ā¹ Run `devtools::test()` or `testthat::test_file()` to see changes.
#> Current value:
#> Code
#> read_local_md(dir)
#> Output
#> ---
#> title: baz
#> ---
#>
#> ```r
#> library(foo)
#> ```
#> āā Skip: āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā
#> Reason: empty test
Created on 2024-02-02 by the reprex package (v2.0.1)
As you can see, the first snapshot captures the title but not the second one, meaning that .onLoad()
was executed once, when rendering for the first time.
Is there a way to unload the package from within .onLoad()
when it's done with the rendering so that it could run .onLoad()
in every snapshot? Defering a detach doesn't make R happy.