Maelle Salmon shows us how to test our R packages within R:
If you’re brand-new to unit testing your R package, I’d recommend reading this chapter from Hadley Wickham’s book about R packages.
There’s an R package called
RUnit
for unit testing, but in the whole post we’ll mention resources around thetestthat
package since it’s the one we use in our packages, and arguably the most popular one.testthat
is great! Don’t hesitate to reads its docs again if you started using it a while ago, since the latest major release added thesetup()
andteardown()
functions to run code before and after all tests, very handy.To setup testing in an existing package i.e. creating the test folder and adding
testthat
as a dependency, runusethis::use_testthat()
. In our WIPpRojects
package, we set up the tests directory for you so you don’t forget. Then, in any case, add new tests for a function usingusethis::use_test()
.The
testthis
package might help make your testing workflow even smoother. In particular,test_this()
“reloads the package and runs tests associated with the currently open R script file.”, and there’s also a function for opening the test file associated with the current R script.
This is an area where I know I need to get better, and Maelle gives us a plethora of tooling for tests.