14 Using tests
When writing your R package, a workflow often looks like:
- Write the code
- use
load_all()
- test the input in the console
- change code
load_all()
These local sanity checks are really important, but also benefit from being formalised in a way so that they run every time you check your package.
This has the following benefits
- Confidence that if you change code you don’t break things
- Confidence from users that your code is robust
14.1 use_testthat()
To get started, we will run:
`use_testthat()`
Which gives us
✔ Adding testthat to Suggests field in DESCRIPTION.
✔ Adding "3" to Config/testthat/edition.
✔ Creating tests/testthat/.
✔ Writing tests/testthat.R.
☐ Call usethis::use_test() to initialize a basic
test file and open it for editing.
See this commit
- What sort of tests do you think we should care about
14.2 Plan for writing tests
re-examine data quality checks
explain moving from less-formal to more formalised approach
demonstrate testing dimensions/names
demonstrate snapshot tests
expect_snapshot(clean_data(raw_education_2014))
- demonstrate vdiffr tests
set.seed(2025-04-11)
<- plot_code(data)
plot_name
test_that("plot works", {
skip_on_cran()
skip_on_ci()
::expect_doppelganger("plot_name", plot_name)
vdiffr })
Circle back to the data quality checks
R packages can be used for other things than CRAN - although this does maybe go against some ideas in this course, the R package structure can be exploited to do some cool things - like perhaps data validation?
R Packages vs Projects: Miles McBain https://milesmcbain.xyz/posts/an-okay-idea/