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
RUnitfor unit testing, but in the whole post we’ll mention resources around the
testthatpackage since it’s the one we use in our packages, and arguably the most popular one.
testthatis great! Don’t hesitate to reads its docs again if you started using it a while ago, since the latest major release added the
teardown()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
testthatas a dependency, run
usethis::use_testthat(). In our WIP
pRojectspackage, we set up the tests directory for you so you don’t forget. Then, in any case, add new tests for a function using
testthispackage 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.