rtestthat

R testthat image file not found for image snapshot


I am trying to use testthat's expect_snapshot_file to test a plotting function that uses ggplot2. I largely copied over the example from the vignette on snapshots, but get an error indicating that the temporary image file created for the test cannot be found.

Here is the test file's code:

save_png <- function(code, width = 400, height = 400) {
  path <- tempfile(fileext = ".png")
  png(path, width = width, height = height)
  on.exit(dev.off())
  code

  path
}

expect_snapshot_plot <- function(name, code) {
  name <- paste0(name, ".png")
  announce_snapshot_file(name = name)
  path <- save_png(code)
  expect_snapshot_file(path, name)
}

test_that("end to end", {
  # OMITTED: code to generate the output `out`

  name = "losses_plot"
  expect_snapshot_plot(name, plot_losses(out))
})

plot_losses is my plotting function, which uses ggplot2:

plot_losses <- function(out) {
  out %>%
    ggplot() +
    geom_point(aes(x, y, color = k))
}

Solution

  • You need to wrap code (the plotting call) with show:

    save_png <- function(code, width = 400, height = 400) {
      path <- tempfile(fileext = ".png")
      png(path, width = width, height = height)
      on.exit(dev.off())
      show(code)  # CHANGE HERE
    
      path
    }
    
    # Everything else the same.