Reputation: 121
I have a custom plotting function of which I'd like to ensure that it's putting out the same plots even after adding additional options to the plot-function.
Unfortunately, the testthat::expect_known_hash
-approach fails because ggplots store information about some environments, which obviously will change when restarting R.
A similar problem appears when testing outputs of function factory, as the closures also carry their environment.
Did anyone encounter this problem, and how did you solve it?
Upvotes: 1
Views: 353
Reputation: 6528
If this is part of test cases you can use package 'vdiffr' that extends 'testthat'. It is used for the latest release of 'ggplot2' for the test cases, so you can look in Github for examples. It also installs an addin in RStudio to manage the saved test cases and do visual comparison of the failed tests. It works nicely, I am using it in my own packages. It uses a simplified svg device to save to disk the reference plots.
A test case might look like this (all the rest is like for 'testthat' cases):
vdiffr::expect_doppelganger("test_001",
ggplot(data = cars, aes(speed, dist)) +
geom_point()
)
In some other cases than plots expect_known_output()
or expect_known_value()
from package 'testthat' might help, but I guess not in every case.
Upvotes: 1
Reputation: 5000
The library compare
allows you to compare different R objects. The package has different functions to detect what the differences are between objects.
compare(plot(0), plot(0))
TRUE
scatter <- ggplot(data=iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point(aes(color=Species, shape=Species))
scatter2 <- ggplot(data=iris, aes(x = Sepal.Length, y = Petal.Width)) + geom_point(aes(color=Species, shape=Species))
compare(scatter, scatter2)
FALSE [TRUE, TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE]
model treated as list
[layers] [1] model treated as character
[scales] model treated as character
[mapping] model treated as list
[mapping] [y] model treated as character
[coordinates] model treated as character
[facet] model treated as character
Upvotes: 2