4141# ' written to the `_snaps` directory but which no longer have
4242# ' corresponding R code to generate them. These dangling files are
4343# ' automatically deleted so they don't clutter the snapshot
44- # ' directory. However we want to preserve snapshot files when the R
45- # ' code wasn't executed because of an unexpected error or because of a
46- # ' [skip()]. Let testthat know about these files by calling
47- # ' `announce_snapshot_file()` before `expect_snapshot_file()`.
44+ # ' directory.
45+ # '
46+ # ' This can cause problems if your test is conditionally executed, either
47+ # ' because of an `if` statement or a [skip()]. To avoid files being deleted in
48+ # ' this case, you can call `announce_snapshot_file()` before the conditional
49+ # ' code.
50+ # '
51+ # ' ```R
52+ # ' test_that("can save a file", {
53+ # ' if (!can_save()) {
54+ # ' announce_snapshot_file(name = "data.txt")
55+ # ' skip("Can't save file")
56+ # ' }
57+ # ' path <- withr::local_tempfile()
58+ # ' expect_snapshot_file(save_file(path, mydata()), "data.txt")
59+ # ' })
60+ # ' ```
4861# '
4962# ' @export
5063# ' @examples
6780# ' }
6881# '
6982# ' # You'd then also provide a helper that skips tests where you can't
70- # ' # be sure of producing exactly the same output
83+ # ' # be sure of producing exactly the same output.
7184# ' expect_snapshot_plot <- function(name, code) {
85+ # ' # Announce the file before touching skips or running `code`. This way,
86+ # ' # if the skips are active, testthat will not auto-delete the corresponding
87+ # ' # snapshot file.
88+ # ' name <- paste0(name, ".png")
89+ # ' announce_snapshot_file(name = name)
90+ # '
7291# ' # Other packages might affect results
7392# ' skip_if_not_installed("ggplot2", "2.0.0")
74- # ' # Or maybe the output is different on some operation systems
93+ # ' # Or maybe the output is different on some operating systems
7594# ' skip_on_os("windows")
7695# ' # You'll need to carefully think about and experiment with these skips
7796# '
78- # ' name <- paste0(name, ".png")
79- # '
80- # ' # Announce the file before touching `code`. This way, if `code`
81- # ' # unexpectedly fails or skips, testthat will not auto-delete the
82- # ' # corresponding snapshot file.
83- # ' announce_snapshot_file(name = name)
84- # '
8597# ' path <- save_png(code)
8698# ' expect_snapshot_file(path, name)
8799# ' }
@@ -97,14 +109,15 @@ expect_snapshot_file <- function(
97109 check_string(path )
98110 check_string(name )
99111 check_bool(cran )
112+ check_variant(variant )
100113
101114 edition_require(3 , " expect_snapshot_file()" )
115+
116+ announce_snapshot_file(name = name )
102117 if (! cran && on_cran()) {
103- skip( " On CRAN " )
118+ return ( invisible () )
104119 }
105120
106- check_variant(variant )
107-
108121 snapshotter <- get_snapshotter()
109122 if (is.null(snapshotter )) {
110123 snapshot_not_available(path )
0 commit comments