R
R packages
Best practices
Testing series · part 1

testthat essentials

Move from manual console checks to automated, reproducible test suites

Set up testthat 3rd edition, structure unit tests with expectations, run them locally and in CI, and build reproducible verification suites.
Published

2026-09-26

Modified

2026-09-27

The problem

Most R developers begin testing interactively in the console. You write a function, call it with sample arguments, glance at the resulting vector or data frame, decide it looks right, and move on.

That works until code changes:

  • A colleague tweaks a helper function, altering missing value handling.
  • An upstream package updates and returns a tibble where base R returned a vector.
  • You refactor months later and forget which edge cases previously broke your logic.

Manual console checks are unrecorded, unrepeatable, and trapped on a single machine. They do not run in continuous integration, cannot prevent pull request regressions, and leave no record anyone could review later.

Automated unit tests replace human memory with executable assertions. They form the base for everything else in this series: test fixtures, mocking, snapshot tests, Shiny tests, and tests as evidence.

The web-repo way

In JavaScript and TypeScript repositories, frameworks like Vitest and Jest make testing an ambient part of development:

// src/format.ts
export function formatRatio(numerator: number, denominator: number): string {
  if (denominator === 0) throw new Error("Denominator cannot be zero");
  return `${((numerator / denominator) * 100).toFixed(1)}%`;
}

// src/format.test.ts
import { describe, it, expect } from "vitest";
import { formatRatio } from "./format";

describe("formatRatio", () => {
  it("formats standard percentages correctly", () => {
    expect(formatRatio(1, 4)).toBe("25.0%");
  });

  it("throws on zero denominator", () => {
    expect(() => formatRatio(1, 0)).toThrow("Denominator cannot be zero");
  });
});

Web repositories rely on three core patterns:

  1. Co-located pairing: Tests mirror source code directly (format.ts ↔︎ format.test.ts).
  2. Fast feedback loops: npm test runs the suite, and watch mode re-runs tests on save.
  3. CI gates: Tests run automatically on every pull request. Broken tests block merges.

The R way

In R, the standard framework is testthat. Together with usethis and devtools, it provides an equivalent development workflow.

1 · Setup with usethis::use_testthat(3)

Set up package testing infrastructure with one command:

usethis::use_testthat(3)

This performs four key actions:

  1. Creates tests/testthat/: The home for all unit test files.

  2. Creates tests/testthat.R: The test harness executed during package checks:

    library(testthat)
    library(yourpackage)
    
    test_check("yourpackage")
  3. Adds testthat (>= 3.0.0) to Suggests in DESCRIPTION.

  4. Sets Config/testthat/edition: 3 in DESCRIPTION: Activates testthat’s 3rd edition.

2 · File pairing with usethis::use_test()

Package code lives in R/<name>.R and its corresponding tests live in tests/testthat/test-<name>.R.

Create or navigate to the paired test file using usethis::use_test():

# With R/format_ratio.R open in RStudio:
usethis::use_test()

# Or specify the name explicitly:
usethis::use_test("format_ratio")

use_test() creates tests/testthat/test-format_ratio.R if it’s missing and opens it. usethis::use_r() goes the other way, from a test file to its code file.

3 · Anatomy of a test: blocks and expectations

Say R/format_ratio.R holds:

format_ratio <- function(numerator, denominator) {
  if (denominator == 0) stop("Denominator cannot be zero")
  sprintf("%.1f%%", numerator / denominator * 100)
}

A test file groups expectations inside test_that() blocks, each describing one behaviour:

test_that("format_ratio() formats percentages to one decimal place", {
  expect_equal(format_ratio(1, 4), "25.0%")
  expect_equal(format_ratio(2, 3), "66.7%")
})

test_that("format_ratio() rejects a zero denominator", {
  expect_error(format_ratio(1, 0), "Denominator cannot be zero")
})

Common expectations cover standard R data structures and conditions:

Expectation Verifies Example
expect_equal(object, expected) Equality within numerical tolerance expect_equal(sqrt(2)^2, 2)
expect_identical(object, expected) Exact equality (no tolerance) expect_identical(1L + 1L, 2L)
expect_error(object, regexp, class) Throws expected error expect_error(log("a"))
expect_warning(object, regexp, class) Signals expected warning expect_warning(as.numeric("a"))
expect_message(object, regexp, class) Emits expected message expect_message(message("ready"))
expect_true(object) / expect_false(object) Scalar boolean condition expect_true(is.data.frame(df))
expect_length(object, n) Length of vector or list expect_length(names(df), 5)
expect_named(object, expected) Vector or list names expect_named(res, c("id", "val"))

What the 3rd edition changes

The 3rd edition modernises testing behaviour:

  • Clearer differences: expect_equal() and expect_identical() use waldo::compare(), which shows exactly which elements or attributes differ.
  • Messages aren’t hidden: the 2nd edition silently dropped messages raised inside a test. The 3rd edition shows them, so an unexpected message gets noticed.
  • Reproducible output: each test runs with fixed settings (80-character width, no colour or Unicode, C language and collation), so output doesn’t change between machines.
  • Deprecated functions: context() is deprecated (the file name gives the context), and expect_is() gives way to expect_type(), expect_s3_class() and expect_s4_class().

4 · Running tests

Run tests at the appropriate scope throughout your day:

Scope Command Purpose
Active file devtools::test_active_file() Quick feedback while editing one file
Single file testthat::test_file("tests/testthat/test-calc.R") Verify a subsystem from the console
Full suite devtools::test() Verify the whole package before committing
Package check devtools::check() / R CMD check Full pre-merge gate locally and in CI

In RStudio, Ctrl+Shift+T (Cmd+Shift+T on a Mac) runs devtools::test(). In CI, R CMD check runs tests/testthat.R; a failing test is a check error, so the pull request goes red.

5 · Skip helpers

Not every test belongs in every environment. Use skip helpers to bypass checks gracefully:

test_that("fetches clinical metadata from remote repository", {
  skip_on_cran()                    # Skip on CRAN to respect network and time limits
  skip_if_offline()                 # Skip if no internet connectivity
  skip_if_not_installed("httr2")    # Skip if an optional dependency is missing

  res <- fetch_clinical_metadata("STUDY-01")
  expect_s3_class(res, "data.frame")
})

Skips are reported as skips, not failures, so the results still show what didn’t run.

6 · Tests outside a package

You do not need a package structure to write unit tests. Shiny apps, Quarto sites, and data pipelines can adopt testthat directly:

  1. Create tests/testthat/ at your repository root.
  2. Add standard test-*.R test files.
  3. Run the directory using:
testthat::test_dir("tests/testthat", stop_on_failure = TRUE)

stop_on_failure = TRUE (the default) makes the call fail when any test fails, which is what a CI step needs. This site does exactly that: its post scripts, such as the one below, have tests that run with test_dir() on every pull request.

7 · Tests as evidence: the GxP angle

In regulated work, “I checked it in the console” isn’t evidence anyone can review. Automated tests are:

  • Repeatable: anyone can re-run them and get the same result.
  • Recorded: a CI run keeps the results together with the commit, the R version and (with renv) the exact package versions.
  • Traceable: a test’s description can reference the requirement it checks.

That makes test results useful evidence in a risk-based validation approach. A later post in this series covers traceability from requirements to tests.

The next posts in the series cover test design (fixtures, temporary state with withr, and mocking), then snapshot tests.

Pitfalls

  • Tests depending on global state or working directory: Never rely on variables left in the global environment or unreset setwd() calls. Each test must run independently in any order.
  • Testing implementation details over interfaces: Assert against public function inputs and outputs. If refactoring an internal loop breaks your tests while external behaviour remains unchanged, your tests are too tightly coupled to implementation.
  • Huge test_that() blocks: thirty expectations under one description make a failure hard to place, and an error (unlike a failed expectation) stops the rest of the block. Give each behaviour its own block.
  • Forgetting the edition: without Config/testthat/edition: 3 in DESCRIPTION, a package’s tests run in the 2nd edition, which silences messages and skips the reproducible-output settings.

Companion code

View first-tests.R · Download

Builds a throwaway package in a temporary directory, configures testthat and helper files with {usethis}, and executes the test suite with {testthat}. Requires {testthat} and {usethis}.

# The testthat loop, end to end: builds a throwaway package in a temporary
# folder, adds a small function and its tests with usethis, and runs the tests
# with testthat.
#
#   Rscript first-tests.R

bmi_code <- c(
  "#' Body mass index",
  "#'",
  "#' @param weight_kg Weight in kilograms.",
  "#' @param height_m Height in metres.",
  "#' @return Weight divided by height squared.",
  "#' @export",
  "bmi <- function(weight_kg, height_m) {",
  "  if (any(height_m <= 0, na.rm = TRUE)) {",
  "    stop(\"`height_m` must be positive.\", call. = FALSE)",
  "  }",
  "  weight_kg / height_m^2",
  "}"
)

bmi_tests <- c(
  "test_that(\"bmi() divides weight by height squared\", {",
  "  expect_equal(bmi(70, 1.75), 22.857, tolerance = 1e-4)",
  "})",
  "",
  "test_that(\"bmi() is vectorised\", {",
  "  expect_length(bmi(c(60, 70, 80), c(1.6, 1.7, 1.8)), 3)",
  "})",
  "",
  "test_that(\"bmi() rejects heights that aren't positive\", {",
  "  expect_error(bmi(70, 0), \"must be positive\")",
  "})",
  "",
  "test_that(\"bmi() keeps missing values missing\", {",
  "  expect_true(is.na(bmi(NA, 1.7)))",
  "})"
)

# Creates the package and returns its path.
make_demo_package <- function(path = file.path(tempdir(), "bmicalc")) {
  usethis::create_package(path, rstudio = FALSE, open = FALSE)
  usethis::with_project(path, {
    usethis::use_testthat(3) # tests/testthat/, tests/testthat.R, edition 3
    usethis::use_r("bmi", open = FALSE) # creates the R/bmi.R file
    usethis::use_test("bmi", open = FALSE) # creates its test file
  })
  writeLines(bmi_code, file.path(path, "R", "bmi.R"))
  writeLines(bmi_tests, file.path(path, "tests", "testthat", "test-bmi.R"))
  path
}

# Loads the package from source and runs its tests (like devtools::test()).
run_demo_tests <- function(path, reporter = testthat::default_reporter()) {
  testthat::test_local(path, reporter = reporter, stop_on_failure = FALSE)
}

# Run only when called as a script (not when sourced by the tests).
if (sys.nframe() == 0L) {
  path <- make_demo_package()
  results <- run_demo_tests(path)
  print(as.data.frame(results)[, c("test", "nb", "failed", "error")])
}

Sources

Package documentation

Web-repo comparison

NoteUpdates
  • 2026-09-26: Removed the end-of-post checklist. Marked package-dependent and environment-dependent blocks as .norun.
  • 2026-09-27: Added a Sources section.
  • 2026-09-27: Added a Companion code section with the full script.