testing-r-packages

Solid

Best practices for writing R package tests using testthat version 3+. Use when writing, organizing, or improving tests for R packages. Covers test structure, expectations, fixtures, snapshots, mocking, and modern testthat 3 patterns including self-sufficient tests, proper cleanup with withr, and snapshot testing.

Testing & QA 396 stars 34 forks Updated today MIT

Install

View on GitHub

Quality Score: 91/100

Stars 20%
87
Recency 20%
100
Frontmatter 20%
70
Documentation 15%
100
Issue Health 10%
50
License 10%
100
Description 5%
100

Skill Content

# Testing R Packages with testthat Modern best practices for R package testing using testthat 3+. ## Initial Setup Initialize testing with testthat 3rd edition: ```r usethis::use_testthat(3) ``` This creates `tests/testthat/` directory, adds testthat to `DESCRIPTION` Suggests with `Config/testthat/edition: 3`, and creates `tests/testthat.R`. ## File Organization **Mirror package structure:** - Code in `R/foofy.R` → tests in `tests/testthat/test-foofy.R` - Use `usethis::use_r("foofy")` and `usethis::use_test("foofy")` to create paired files **Special files:** - `helper-*.R` - Helper functions and custom expectations, sourced before tests - `setup-*.R` - Run during `R CMD check` only, not during `load_all()` - `fixtures/` - Static test data files accessed via `test_path()` ## Test Structure Tests follow a three-level hierarchy: **File → Test → Expectation** ### Standard Syntax ```r test_that("descriptive behavior", { result <- my_function(input) expect_equal(result, expected_value) }) ``` **Test descriptions** should read naturally and describe behavior, not implementation. ### BDD Syntax (describe/it) For behavior-driven development, use `describe()` and `it()`: ```r describe("matrix()", { it("can be multiplied by a scalar", { m1 <- matrix(1:4, 2, 2) m2 <- m1 * 2 expect_equal(matrix(1:4 * 2, 2, 2), m2) }) it("can be transposed", { m <- matrix(1:4, 2, 2) expect_equal(t(m), matrix(c(1, 3, 2, 4), 2, 2)) }) }) ``` **Key features:**...

Details

Author
posit-dev
Repository
posit-dev/skills
Created
6 months ago
Last Updated
today
Language
R
License
MIT

Similar Skills

Semantically similar based on skill content — not just same category