Agent skill

Testing R Packages

by quarto-dev in quarto-dev/quarto-r

Best practices for writing R package tests using testthat version 3+.

MITAuto-check passedTesting & QA

Install Testing R Packages

skills CLI
$ npx skills add quarto-dev/quarto-r --skill testing-r-packages -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install quarto-dev/quarto-r testing-r-packages --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/quarto-dev/quarto-r.git skills-src && mkdir -p .claude/skills && cp -r skills-src/.claude/skills/testing-r-packages .claude/skills/testing-r-packages && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
testing-r-packages
GitHub stars
160
Used in
1 other repo
Token cost
~2.8k tokens
SKILL.md length
589 words
Files
6 (incl. references)
Skills in repo
10
Repo updated
First seen
Licence
MIT

At a glance

Best practices for writing R package tests using testthat version 3+.

  • Works in 5 steps: Self-Sufficient Tests → Self-Contained Tests (Cleanup Side… → Plan for Test Failure → …
  • Improving tests for R packages
  • SKILL.md covers Initial Setup, File Organization, Test Structure and Running Tests, plus 7 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md

What it does

Testing R Packages is an agent skill from quarto-dev/quarto-r. 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.

Its SKILL.md is about 2.8k tokens, which your agent loads only when the skill is triggered. The skill folder holds 6 other files, including reference files (for example `references/advanced.md`, `references/bdd.md` and `references/fixtures.md`).

It sits in Testing & QA. The repository describes itself as: R interface to quarto-cli. The licence is MIT.

When your agent uses it

  • Improving tests for R packages

Example prompts

  • “/testing-r-packages”

Workflow steps

5 steps, taken from the step headings in SKILL.md.

  1. Self-Sufficient Tests
  2. Self-Contained Tests (Cleanup Side Effects)
  3. Plan for Test Failure
  4. Repetition is Acceptable
  5. Use devtools::load_all() Workflow

What it can do on your machine

Read from SKILL.md and the folder at commit bd2329a. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are r).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Testing R Packages loads about 2.8k tokens when it runs, and up to ~12k if it reads all its reference files. Until then it costs about 83 tokens; SKILL.md has 589 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~83
When it runs · the whole SKILL.md, loaded when a task matches
~2.8k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~12k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from quarto-dev/quarto-r at commit bd2329a, republished under its MIT licence (© quarto-dev). 589 words, ~2,783 tokens.

Download SKILL.mdSave it as .claude/skills/testing-r-packages/SKILL.md (or your agent's skills folder). This skill also uses 5 other files; get the full folder from GitHub.
name
testing-r-packages
description
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.
metadata.author
Garrick Aden-Buie (@gadenbuie)
metadata.version
1.1
license
MIT

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:

  • describe() groups related specifications for a component
  • it() defines individual specifications (like test_that())
  • Supports nesting for hierarchical organization
  • it() without code creates pending test placeholders

Use describe() to verify you implement the right things, use test_that() to ensure you do things right.

See references/bdd.md for comprehensive BDD patterns, nested specifications, and test-first workflows.

Running Tests

Three scales of testing:

Micro (interactive development):

r
devtools::load_all()
expect_equal(foofy(...), expected)

Mezzo (single file):

r
testthat::test_file("tests/testthat/test-foofy.R")
# RStudio: Ctrl/Cmd + Shift + T

Macro (full suite):

r
devtools::test()    # Ctrl/Cmd + Shift + T
devtools::check()   # Ctrl/Cmd + Shift + E

Core Expectations

Equality
r
expect_equal(10, 10 + 1e-7)      # Allows numeric tolerance
expect_identical(10L, 10L)       # Exact match required
expect_all_equal(x, expected)    # Every element matches (v3.3.0+)
Errors, Warnings, Messages
r
expect_error(1 / "a")
expect_error(bad_call(), class = "specific_error_class")
expect_no_error(valid_call())

expect_warning(deprecated_func())
expect_no_warning(safe_func())

expect_message(informative_func())
expect_no_message(quiet_func())
Pattern Matching
r
expect_match("Testing is fun!", "Testing")
expect_match(text, "pattern", ignore.case = TRUE)
Structure and Type
r
expect_length(vector, 10)
expect_type(obj, "list")
expect_s3_class(model, "lm")
expect_s4_class(obj, "MyS4Class")
expect_r6_class(obj, "MyR6Class")      # v3.3.0+
expect_shape(matrix, c(10, 5))         # v3.3.0+
Sets and Collections
r
expect_setequal(x, y)           # Same elements, any order
expect_contains(fruits, "apple") # Subset check (v3.2.0+)
expect_in("apple", fruits)       # Element in set (v3.2.0+)
expect_disjoint(set1, set2)      # No overlap (v3.3.0+)
Logical
r
expect_true(condition)
expect_false(condition)
expect_all_true(vector > 0)      # All elements TRUE (v3.3.0+)
expect_all_false(vector < 0)     # All elements FALSE (v3.3.0+)

Design Principles

1. Self-Sufficient Tests

Each test should contain all setup, execution, and teardown code:

r
# Good: self-contained
test_that("foofy() works", {
  data <- data.frame(x = 1:3, y = letters[1:3])
  result <- foofy(data)
  expect_equal(result$x, 1:3)
})

# Bad: relies on ambient state
dat <- data.frame(x = 1:3, y = letters[1:3])
test_that("foofy() works", {
  result <- foofy(dat)  # Where did 'dat' come from?
  expect_equal(result$x, 1:3)
})
2. Self-Contained Tests (Cleanup Side Effects)

Use withr to manage state changes:

r
test_that("function respects options", {
  withr::local_options(my_option = "test_value")
  withr::local_envvar(MY_VAR = "test")
  withr::local_package("jsonlite")

  result <- my_function()
  expect_equal(result$setting, "test_value")
  # Automatic cleanup after test
})

Common withr functions:

  • local_options() - Temporarily set options
  • local_envvar() - Temporarily set environment variables
  • local_tempfile() - Create temp file with automatic cleanup
  • local_tempdir() - Create temp directory with automatic cleanup
  • local_package() - Temporarily attach package
3. Plan for Test Failure

Write tests assuming they will fail and need debugging:

  • Tests should run independently in fresh R sessions
  • Avoid hidden dependencies on earlier tests
  • Make test logic explicit and obvious
4. Repetition is Acceptable

Repeat setup code in tests rather than factoring it out. Test clarity is more important than avoiding duplication.

5. Use devtools::load_all() Workflow

During development:

  • Use devtools::load_all() instead of library()
  • Makes all functions available (including unexported)
  • Automatically attaches testthat
  • Eliminates need for library() calls in tests
Show full SKILL.md (246 more words)Show less

Snapshot Testing

For complex output that's difficult to verify programmatically, use snapshot tests. See references/snapshots.md for complete guide.

Basic pattern:

r
test_that("error message is helpful", {
  expect_snapshot(
    error = TRUE,
    validate_input(NULL)
  )
})

Snapshots stored in tests/testthat/_snaps/.

Workflow:

r
devtools::test()                    # Creates new snapshots
testthat::snapshot_review('name')   # Review changes
testthat::snapshot_accept('name')   # Accept changes

Test Fixtures and Data

Three approaches for test data:

1. Constructor functions - Create data on-demand:

r
new_sample_data <- function(n = 10) {
  data.frame(id = seq_len(n), value = rnorm(n))
}

2. Local functions with cleanup - Handle side effects:

r
local_temp_csv <- function(data, env = parent.frame()) {
  path <- withr::local_tempfile(fileext = ".csv", .local_envir = env)
  write.csv(data, path, row.names = FALSE)
  path
}

3. Static fixture files - Store in fixtures/ directory:

r
data <- readRDS(test_path("fixtures", "sample_data.rds"))

See references/fixtures.md for detailed fixture patterns.

Mocking

Replace external dependencies during testing using local_mocked_bindings(). See references/mocking.md for comprehensive mocking strategies.

Basic pattern:

r
test_that("function works with mocked dependency", {
  local_mocked_bindings(
    external_api = function(...) list(status = "success", data = "mocked")
  )

  result <- my_function_that_calls_api()
  expect_equal(result$status, "success")
})

Common Patterns

Testing Errors with Specific Classes
r
test_that("validation catches errors", {
  expect_error(
    validate_input("wrong_type"),
    class = "vctrs_error_cast"
  )
})
Testing with Temporary Files
r
test_that("file processing works", {
  temp_file <- withr::local_tempfile(
    lines = c("line1", "line2", "line3")
  )

  result <- process_file(temp_file)
  expect_equal(length(result), 3)
})
Testing with Modified Options
r
test_that("output respects width", {
  withr::local_options(width = 40)

  output <- capture_output(print(my_object))
  expect_lte(max(nchar(strsplit(output, "\n")[[1]])), 40)
})
r
test_that("str_trunc() handles all directions", {
  trunc <- function(direction) {
    str_trunc("This string is moderately long", direction, width = 20)
  }

  expect_equal(trunc("right"), "This string is mo...")
  expect_equal(trunc("left"), "...erately long")
  expect_equal(trunc("center"), "This stri...ely long")
})
Custom Expectations in Helper Files
r
# In tests/testthat/helper-expectations.R
expect_valid_user <- function(user) {
  expect_type(user, "list")
  expect_named(user, c("id", "name", "email"))
  expect_type(user$id, "integer")
  expect_match(user$email, "@")
}

# In test file
test_that("user creation works", {
  user <- create_user("test@example.com")
  expect_valid_user(user)
})

File System Discipline

Always write to temp directory:

r
# Good
output <- withr::local_tempfile(fileext = ".csv")
write.csv(data, output)

# Bad - writes to package directory
write.csv(data, "output.csv")

Access test fixtures with test_path():

r
# Good - works in all contexts
data <- readRDS(test_path("fixtures", "data.rds"))

# Bad - relative paths break
data <- readRDS("fixtures/data.rds")

Advanced Topics

For advanced testing scenarios, see:

testthat 3 Modernizations

When working with testthat 3 code, prefer modern patterns:

Deprecated → Modern:

  • context() → Remove (duplicates filename)
  • expect_equivalent() → expect_equal(ignore_attr = TRUE)
  • with_mock() → local_mocked_bindings()
  • is_null(), is_true(), is_false() → expect_null(), expect_true(), expect_false()

New in testthat 3:

  • Edition system (Config/testthat/edition: 3)
  • Improved snapshot testing
  • waldo::compare() for better diff output
  • Unified condition handling
  • local_mocked_bindings() works with byte-compiled code
  • Parallel test execution support

Quick Reference

Initialize: usethis::use_testthat(3)

Run tests: devtools::test() or Ctrl/Cmd + Shift + T

Create test file: usethis::use_test("name")

Review snapshots: testthat::snapshot_review()

Accept snapshots: testthat::snapshot_accept()

Find slow tests: devtools::test(reporter = "slow")

Shuffle tests: devtools::test(shuffle = TRUE)

© quarto-dev, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 5 other files (references) in .claude/skills/testing-r-packages of quarto-dev/quarto-r.

  • SKILL.md
  • references/advanced.md
  • references/bdd.md
  • references/fixtures.md
  • references/mocking.md
  • references/snapshots.md

Open the folder on GitHubat commit bd2329a

Used in 1 other repository

We found 1 copy of this SKILL.md (exact, near-identical or edited) in other folders, from 1 other GitHub owner. This page covers the copy in quarto-dev/quarto-r, which our catalogue first saw on October 7, 2026.

Compare with similar skills

Testing R Packages next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Testing R Packages compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Testing R Packages this skillquarto-dev/quarto-r1601 repos~2.8kAutomated safety check: PassMIT
Web Application Testinganthropics/skills180k51 repos~966Automated safety check: PassApache-2.0
Diagnosing Bugsfossasia/eventyay-interpretation1.6k31 repos~2.1kAutomated safety check: PassApache-2.0
TDDfossasia/eventyay-interpretation1.6k28 repos~1.1kAutomated safety check: PassApache-2.0
TDD WorkflowhellangleZ/burn-in-cceverywhere-ralph11211 repos~2.4kAutomated safety check: PassNone
TDDsanity-io/sanity6.4k20 repos~1kAutomated safety check: PassMIT

Similar skills

  • Web Application Testing

    anthropics/skills

    Official

    Tests local web applications with Python Playwright scripts, checking frontend behavior, capturing screenshots and reading browser console logs.

    180k GitHub starsUsed in 51 repos~966 tokens
    Testing & QAAuto-check passed
  • Diagnosing Bugs

    fossasia/eventyay-interpretation

    Diagnosis loop for hard bugs and performance regressions. An agent skill from fossasia/eventyay-interpretation.

    1.6k GitHub starsUsed in 31 repos~2.1k tokens
    Testing & QAAuto-check passed
  • TDD

    fossasia/eventyay-interpretation

    Test-driven development. An agent skill from fossasia/eventyay-interpretation.

    1.6k GitHub starsUsed in 28 repos~1.1k tokens
    Testing & QAAuto-check passed
  • TDD Workflow

    hellangleZ/burn-in-cceverywhere-ralph

    A skill your agent uses when writing new features, fixing bugs, or refactoring code.

    112 GitHub starsUsed in 11 repos~2.4k tokens
    Testing & QAAuto-check passed
  • TDD

    sanity-io/sanity

    Official

    Test-driven development with red-green-refactor loop. An agent skill from sanity-io/sanity.

    6.4k GitHub starsUsed in 20 repos~1k tokens
    Testing & QAAuto-check passed
  • Context Driven Development

    Ibrahim-3d/orchestrator-supaconductor

    A skill your agent uses when working with Conductor's context-driven development methodology, managing project context artifacts, or understanding the relationship between product.md, tech-stack.md…

    380 GitHub starsUsed in 8 repos~2.9k tokens
    Testing & QAAuto-check passed

More from quarto-dev/quarto-r

All 10 skills in this repo
  • Release Post

    quarto-dev/quarto-r

    Create professional package release blog posts following Tidyverse or Shiny blog conventions.

    160 GitHub starsUsed in 1 repo~2.5k tokens
    Auto-check passed
  • Create Release Checklist

    quarto-dev/quarto-r

    Create a release checklist and GitHub issue for an R package.

    160 GitHub starsUsed in 1 repo~1.9k tokens
    Auto-check: notes
  • Alt Text

    quarto-dev/quarto-r

    Generate and improve accessible alt text for data visualizations and images in R packages and Quarto documents.

    160 GitHub starsUsed in 1 repo~1.7k tokens
    Auto-check passed
  • CLI

    quarto-dev/quarto-r

    Comprehensive R package for command-line interface styling, semantic messaging, and user communication.

    160 GitHub starsUsed in 1 repo~2.8k tokens
    Auto-check passed
  • Quarto Authoring

    quarto-dev/quarto-r

    A skill your agent uses when the user is explicitly working with Quarto, .qmd files, quarto.yml, Quarto projects, or Quarto features such as callouts, cross-references, citations, Mermaid diagrams…

    160 GitHub starsUsed in 1 repo~1.9k tokens
    Auto-check passed
  • Cran Extrachecks

    quarto-dev/quarto-r

    Prepare R packages for CRAN submission by checking for common ad-hoc requirements not caught by devtools::check().

    160 GitHub starsUsed in 1 repo~3.7k tokens
    Auto-check passed

Categories

Questions about Testing R Packages

What does Testing R Packages do?

Best practices for writing R package tests using testthat version 3+. Testing R Packages is an agent skill from quarto-dev/quarto-r. Best practices for writing R package tests using testthat version 3+.

When should I use Testing R Packages?

Testing R Packages fits situations like: improving tests for R packages.

How do I install Testing R Packages in Claude Code?

Run `npx skills add quarto-dev/quarto-r --skill testing-r-packages -a claude-code`. Or copy the skill folder (.claude/skills/testing-r-packages in quarto-dev/quarto-r) into .claude/skills/testing-r-packages in your project. Claude Code loads it when a task matches its description.

How do I install Testing R Packages in Codex?

Run `npx skills add quarto-dev/quarto-r --skill testing-r-packages -a codex`. Or copy the skill folder (.claude/skills/testing-r-packages in quarto-dev/quarto-r) into .agents/skills/testing-r-packages in your project. Codex loads it when a task matches its description.

Can I use Testing R Packages in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add quarto-dev/quarto-r --skill testing-r-packages -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/testing-r-packages, .gemini/skills/testing-r-packages, .github/skills/testing-r-packages and .opencode/skills/testing-r-packages in your project.

What does Testing R Packages need to run?

SKILL.md names no scripts, command-line tools or credentials: Testing R Packages is instructions for the agent only.

Does Testing R Packages access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Testing R Packages safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Testing R Packages use?

Testing R Packages is published under the MIT licence (declared in SKILL.md). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Testing R Packages use?

About 2.8k tokens (SKILL.md is roughly 11k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 8.8k tokens, read only when the agent opens those files.

What are the alternatives to Testing R Packages?

Skills that share tags, products or a category with Testing R Packages: Web Application Testing (anthropics/skills, 180k stars), Diagnosing Bugs (fossasia/eventyay-interpretation, 1.6k stars), TDD (fossasia/eventyay-interpretation, 1.6k stars) and TDD Workflow (hellangleZ/burn-in-cceverywhere-ralph, 112 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Testing R Packages?

quarto-dev (a GitHub organization) maintains it in quarto-dev/quarto-r, which has 160 GitHub stars. The repository holds 10 skills in this directory. The repository was last updated on September 10, 2026.

Source: quarto-dev/quarto-r on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.