Avoid repeatedly calling the same code in multiple test files?

Is there a way, using testthat, to have some code run to create one or more objects that are then used for testing across a number of test files, such that the code is only run once?

Use case

I have a package, gratia, which does useful stuff with models fitted in the mgcv package. As such almost all my tests require some GAM models to be fitted. I currently fit these models at the head of each test script, but inevitably I am refitting the same model multiple times over the suite of tests for the package.

Ideally, I don't want to store models as objects in the package (they not huge objects, but they not small either) mostly because mgcv does update from time to time and I am concerned that I would have models that were valid in say r-release that are different to the ones in r-devel or r-oldrelease which would cause complications when testing on different versions of R. There's also the administrative burden of maintaining these models...

Is this possible with testthat? Have I overlooked something? Other suggestions on how to avoid repeatedly calling the same code in multiple test files?

1 Like

Have you tried defining your common code in tests/testthat/setup-xyz.R and tests/testthat/teardown-xyz.R files?

2 Likes

Thanks @neilcaithness. That's what I'd missed. I'd seen setup() and teardown() but they run for each test. I might suggest/provide some additional text to highlight the setup-xyz.R option in the help for teardown().

3 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.