Search code examples
runit-testingggplot2testthat

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 ?


Solution

  • 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)
    })