14  Using tests

When writing your R package, a workflow often looks like:

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

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

Your Turn
  • 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_name <- plot_code(data)

test_that("plot works", {
  skip_on_cran()
  skip_on_ci()
  vdiffr::expect_doppelganger("plot_name", plot_name)
})
  • 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/