John
John

Reputation: 1947

Test saving ggplots

I'm creating bunch of tests for ggplots. I included things like checking labels, if the output object is ggplot etc. But I have no idea how to test if the plot was saved using testthat and ggsave. Do you have any idea how it can be done ?

Upvotes: 0

Views: 142

Answers (1)

teunbrand
teunbrand

Reputation: 38023

Here is a way to test based on file size. If the file doesn't exist it is NA and if it does exist it should be > 0.

library(testthat)
library(ggplot2)

test_that("plot is saved to file", {
  file <- tempfile(fileext = ".png")
  expect_equal(file.size(file), NA_real_)
  
  plot <- ggplot(mtcars, aes(wt, mpg)) +
    geom_point()
  
  ggsave(file, plot, "png")
  
  expect_true(file.size(file) > 0)
  
  unlink(file)
})

Upvotes: 2

Related Questions