Search code examples
rplotdevtoolsr-packagetestthat

Error: "no current device to record from" for base R plot test in devtools::test()


I have written a simple test in an R package to check classes of plots. It looks something like this:

test_that("test works", {
  base_r_plot <- recordPlot(plot(1))
  expect_equal(class(base_r_plot), "recordedplot")
})

If I try and run this via devtools::test() I get:

Error in `recordPlot(plot(1))`: no current device to record from

Why is that and how can I remedy this?


Solution

  • In an interactive session, graphics devices tend to open "on their own". Running tests is, however, apparently not the same thing and a device e.g. pdf() needs to be opened manually. Setting it to pdf(NULL) will also prevent writing a superfluous Rplots.pdf.

    test_that("test works", {
      pdf(NULL) # prevent writing Rplots.pdf
      base_r_plot <- recordPlot(plot(1))
      dev.off()
      expect_equal(class(base_r_plot), "recordedplot")
    })