write-testthat-tests
Write comprehensive testthat (edition 3) tests for R package functions. Covers test organization, expectations, fixtures, mocking, snapshot tests, parameterized tests, and achieving high coverage. Use when adding tests for new package functions, increasing test coverage for existing code, writing regression tests for bug fixes, or setting up test infrastructure for a package that lacks it.
Best use case
write-testthat-tests is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Write comprehensive testthat (edition 3) tests for R package functions. Covers test organization, expectations, fixtures, mocking, snapshot tests, parameterized tests, and achieving high coverage. Use when adding tests for new package functions, increasing test coverage for existing code, writing regression tests for bug fixes, or setting up test infrastructure for a package that lacks it.
Teams using write-testthat-tests should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/write-testthat-tests/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How write-testthat-tests Compares
| Feature / Agent | write-testthat-tests | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Write comprehensive testthat (edition 3) tests for R package functions. Covers test organization, expectations, fixtures, mocking, snapshot tests, parameterized tests, and achieving high coverage. Use when adding tests for new package functions, increasing test coverage for existing code, writing regression tests for bug fixes, or setting up test infrastructure for a package that lacks it.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# Write testthat Tests
Create comprehensive tests for R package functions using testthat edition 3.
## When to Use
- Adding tests for new package functions
- Increasing test coverage for existing code
- Writing regression tests for bug fixes
- Setting up test infrastructure for a new package
## Inputs
- **Required**: R functions to test
- **Required**: Expected behavior and edge cases
- **Optional**: Test fixtures or sample data
- **Optional**: Target coverage percentage (default: 80%)
## Procedure
### Step 1: Set Up Test Infrastructure
If not already done:
```r
usethis::use_testthat(edition = 3)
```
This creates `tests/testthat.R` and `tests/testthat/` directory.
**Got:** `tests/testthat.R` and `tests/testthat/` directory created. DESCRIPTION has `Config/testthat/edition: 3` set.
**If fail:** If usethis is not available, manually create `tests/testthat.R` containing `library(testthat); library(packagename); test_check("packagename")` and add `tests/testthat/` directory.
### Step 2: Create Test File
```r
usethis::use_test("function_name")
```
This creates `tests/testthat/test-function_name.R` with a template.
**Got:** Test file created at `tests/testthat/test-function_name.R` with a placeholder `test_that()` block ready to fill in.
**If fail:** If `usethis::use_test()` is not available, manually create the file. Follow the naming convention `test-<function_name>.R`.
### Step 3: Write Basic Tests
```r
test_that("weighted_mean computes correct result", {
expect_equal(weighted_mean(1:3, c(1, 1, 1)), 2)
expect_equal(weighted_mean(c(10, 20), c(1, 3)), 17.5)
})
test_that("weighted_mean handles NA values", {
expect_equal(weighted_mean(c(1, NA, 3), c(1, 1, 1), na.rm = TRUE), 2)
expect_true(is.na(weighted_mean(c(1, NA, 3), c(1, 1, 1), na.rm = FALSE)))
})
test_that("weighted_mean validates input", {
expect_error(weighted_mean("a", 1), "numeric")
expect_error(weighted_mean(1:3, 1:2), "length")
})
```
**Got:** Basic tests cover correct output for typical inputs, NA handling behavior, and input validation error messages.
**If fail:** If tests fail immediately, verify the function is loaded (`devtools::load_all()`). If error messages do not match, use a regex pattern in `expect_error()` instead of an exact string.
### Step 4: Test Edge Cases
```r
test_that("weighted_mean handles edge cases", {
# Empty input
expect_error(weighted_mean(numeric(0), numeric(0)))
# Single value
expect_equal(weighted_mean(5, 1), 5)
# Zero weights
expect_true(is.nan(weighted_mean(1:3, c(0, 0, 0))))
# Very large values
expect_equal(weighted_mean(c(1e15, 1e15), c(1, 1)), 1e15)
# Negative weights
expect_error(weighted_mean(1:3, c(-1, 1, 1)))
})
```
**Got:** Edge cases are covered: empty input, single values, zero weights, extreme values, and invalid inputs. Each edge case has a clear expected behavior.
**If fail:** If the function does not handle an edge case as expected, decide whether to fix the function or adjust the test. Document the intended behavior for ambiguous cases.
### Step 5: Use Fixtures for Complex Tests
Create `tests/testthat/fixtures/` for test data:
```r
# tests/testthat/helper.R (loaded automatically)
create_test_data <- function() {
data.frame(
x = c(1, 2, 3, NA, 5),
group = c("a", "a", "b", "b", "b")
)
}
```
```r
# In test file
test_that("process_data works with grouped data", {
test_data <- create_test_data()
result <- process_data(test_data)
expect_s3_class(result, "data.frame")
expect_equal(nrow(result), 2)
})
```
**Got:** Fixtures provide consistent test data across multiple test files. Helper functions in `tests/testthat/helper.R` are loaded automatically by testthat.
**If fail:** If helper functions are not found, ensure the file is named `helper.R` (not `helpers.R`) and is located in `tests/testthat/`. Restart the R session if needed.
### Step 6: Mock External Dependencies
```r
test_that("fetch_data handles API errors", {
local_mocked_bindings(
api_call = function(...) stop("Connection refused")
)
expect_error(fetch_data("endpoint"), "Connection refused")
})
test_that("fetch_data returns parsed data", {
local_mocked_bindings(
api_call = function(...) list(data = list(value = 42))
)
result <- fetch_data("endpoint")
expect_equal(result$value, 42)
})
```
**Got:** External dependencies (APIs, databases, network calls) are mocked so tests run without real connections. Mock return values exercise the function's data processing logic.
**If fail:** If `local_mocked_bindings()` fails, ensure the function being mocked is accessible in the test scope. For functions in other packages, use the `.package` argument.
### Step 7: Snapshot Tests for Complex Output
```r
test_that("format_report produces expected output", {
expect_snapshot(format_report(test_data))
})
test_that("plot_results creates expected plot", {
expect_snapshot_file(
save_plot(plot_results(test_data), "test-plot.png"),
"expected-plot.png"
)
})
```
**Got:** Snapshot files are created in `tests/testthat/_snaps/`. First run creates the baseline; subsequent runs compare against it.
**If fail:** If snapshots fail after an intentional change, update them with `testthat::snapshot_accept()`. For cross-platform differences, use the `variant` parameter to maintain platform-specific snapshots.
### Step 8: Use Skip Conditions
```r
test_that("database query works", {
skip_on_cran()
skip_if_not(has_db_connection(), "No database available")
result <- query_db("SELECT 1")
expect_equal(result[[1]], 1)
})
test_that("parallel computation works", {
skip_on_os("windows")
skip_if(parallel::detectCores() < 2, "Need multiple cores")
result <- parallel_compute(1:100)
expect_length(result, 100)
})
```
**Got:** Tests that require special environments (network, database, multiple cores) are guarded with skip conditions. These tests run locally but are skipped on CRAN or restricted CI environments.
**If fail:** If tests fail on CRAN or CI but pass locally, add the appropriate `skip_on_cran()`, `skip_on_os()`, or `skip_if_not()` guard at the top of the `test_that()` block.
### Step 9: Run Tests and Check Coverage
```r
# Run all tests
devtools::test()
# Run specific test file
devtools::test_active_file() # in RStudio
testthat::test_file("tests/testthat/test-function_name.R")
# Check coverage
covr::package_coverage()
covr::report()
```
**Got:** All tests pass with `devtools::test()`. Coverage report shows the target percentage is met (aim for >80%).
**If fail:** If tests fail, read the test output for specific assertion failures. If coverage is below target, use `covr::report()` to identify untested code paths and add tests for them.
## Validation
- [ ] All tests pass with `devtools::test()`
- [ ] Coverage exceeds target percentage
- [ ] Every exported function has at least one test
- [ ] Error conditions are tested
- [ ] Edge cases are covered (NA, NULL, empty, boundary values)
- [ ] No tests depend on external state or order of execution
## Pitfalls
- **Tests depending on each other**: Each `test_that()` block must be independent
- **Hardcoded file paths**: Use `testthat::test_path()` for test fixtures
- **Floating point comparison**: Use `expect_equal()` (has tolerance) not `expect_identical()`
- **Testing private functions**: Test through the public API when possible. Use `:::` sparingly.
- **Snapshot tests in CI**: Snapshots are platform-sensitive. Use `variant` parameter for cross-platform.
- **Forgetting `skip_on_cran()`**: Tests requiring network, databases, or long runtime must skip on CRAN
## Examples
```r
# Pattern: test file mirrors R/ file
# R/weighted_mean.R -> tests/testthat/test-weighted_mean.R
# Pattern: descriptive test names
test_that("weighted_mean returns NA when na.rm = FALSE and input contains NA", {
result <- weighted_mean(c(1, NA), c(1, 1), na.rm = FALSE)
expect_true(is.na(result))
})
# Pattern: testing warnings
test_that("deprecated_function emits deprecation warning", {
expect_warning(deprecated_function(), "deprecated")
})
```
## Related Skills
- `create-r-package` - set up test infrastructure as part of package creation
- `write-roxygen-docs` - document the functions you test
- `setup-github-actions-ci` - run tests automatically on push
- `submit-to-cran` - CRAN requires tests to pass on all platformsRelated Skills
write-vignette
Create R package vignettes using R Markdown or Quarto. Covers vignette setup, YAML configuration, code chunk options, building and testing, and CRAN requirements for vignettes. Use when adding a Getting Started tutorial, documenting complex workflows spanning multiple functions, creating domain-specific guides, or when CRAN submission requires user-facing documentation beyond function help pages.
write-validation-documentation
Write IQ/OQ/PQ validation documentation for computerized systems in regulated environments. Covers protocols, reports, test scripts, deviation handling, and approval workflows. Use when validating R or other software for regulated use, preparing for a regulatory audit, documenting qualification of computing environments, or creating and updating validation protocols and reports for new or re-qualified systems.
write-standard-operating-procedure
Write a GxP-compliant Standard Operating Procedure (SOP). Covers regulatory SOP template structure (purpose, scope, definitions, responsibilities, procedure, references, revision history), approval workflow design, periodic review scheduling, and operational procedures for system use. Use when a new validated system requires operational procedures, when existing informal procedures need formalisation, when an audit finding cites missing procedures, when a change control triggers SOP updates, or when periodic review identifies outdated procedural content.
write-roxygen-docs
Write roxygen2 documentation for R package functions, datasets, and classes. Covers all standard tags, cross-references, examples, and generating NAMESPACE entries. Follows tidyverse documentation style. Use when adding documentation to new exported functions, documenting internal helpers or datasets, documenting S3/S4/R6 classes and methods, or fixing documentation-related R CMD check notes.
write-incident-runbook
Create structured incident runbooks with diagnostic steps, resolution procedures, escalation paths, and communication templates for effective incident response. Use when documenting response procedures for recurring alerts, standardizing incident response across an on-call rotation, reducing MTTR with clear diagnostic steps, creating training materials for new team members, or linking alert annotations directly to resolution procedures.
write-helm-chart
Create production-ready Helm charts for Kubernetes application deployment with templating, values management, chart dependencies, hooks, and testing. Covers chart structure, Go template syntax, values.yaml design, chart repositories, versioning, and best practices for maintainable and reusable charts. Use when packaging a Kubernetes application for repeatable deployments, parameterizing manifests for multiple environments, managing complex multi-component applications with dependencies, or standardizing deployment practices with versioned rollback capability across teams.
write-continue-here
Write a CONTINUE_HERE.md file capturing current session state so a fresh Claude Code session can pick up where this one left off. Covers assessing recent work, structuring the continuation file with objective, completed, in-progress, next-steps, and context sections, and verifying the file is actionable. Use when ending a session with unfinished work, handing off context between sessions, or preserving task state that git alone cannot capture.
write-claude-md
Create an effective CLAUDE.md file that provides project-specific instructions to AI coding assistants. Covers structure, common sections, do/don't patterns, and integration with MCP servers and agent definitions. Use when starting a new project where AI assistants will be used, improving AI behavior on an existing project, documenting project conventions and constraints, or integrating MCP servers or agent definitions into a project workflow.
run-puzzle-tests
Run jigsawR test suite via WSL R. Supports full suite, filtered by pattern, or single file. Interprets pass/fail/skip counts and identifies failing tests. Never use `--vanilla` (renv needs `.Rprofile` to activate). Use after R source changes, after adding a puzzle type or feature, before commits, or when debugging a specific failure.
skill-name-here
One to three sentences describing what this skill accomplishes, followed by key activation triggers. This field is the primary mechanism agents use to decide whether to activate the skill — it is read during discovery before the full body is loaded. Start with a verb. Include the most important "when to use" conditions inline. Max 1024 characters.
vishnu-bhaga
Preservation and sustenance — maintaining working state under perturbation, memory anchoring, consistency enforcement, and protective stabilization. Maps Vishnu's sustaining presence to AI reasoning: holding what works steady, anchoring verified knowledge against drift, and ensuring continuity through change. Use when a working approach is at risk from scope creep, when context drift threatens verified knowledge, after shiva-bhaga dissolution to protect what survived, when a long session risks losing earlier decisions through context compression, or before making changes to a currently functioning system.
version-ml-data
Version machine learning datasets using DVC (Data Version Control) with remote storage backends, build reproducible data pipelines with dependency tracking, integrate with Git workflows, and ensure data lineage for model reproducibility. Use when versioning large datasets that do not fit in Git, tracking data changes alongside code changes, ensuring ML experiment reproducibility, sharing datasets across team members, or auditing data lineage for compliance requirements.