Reusing variables across unit tests with testthat. Is there an acceptable practice to avoid recreating computationally expensive variables

Viewed 113

I am creating an R package, where I have a function that creates an object and a function that makes a plot based on the object.

Example:

objA <- create_obj(sample)
plot_obj(objA)

I have some tests (using testthat) on the first function, eg:

objA <- create_obj(sample)
expect_value(length(objA), 10)

Now I want to test plot_obj(). I need an object to test it on, but creating a new objA is time consuming (seconds).

Can I make objA accessible to other tests (in other files) after the first tests have passed, so I can use it to test plot_obj() without recreating it?

(I suppose I could put objA <- create_obj(sample) in setup.R, but then I would use the function before having tested it).

1 Answers

Here's the workaround I've settled on for now:

in ´tests/testthat/setup.R`:

try({
    objA <- create_obj(sample)
}, silent = TRUE)

This way, I'll still run my tests if create_obj(sample) crashes. I still create objA twice though: once in setup and once in the unit test of create_obj.

Related