Use when writing or running tests for R code, setting up testthat, or following TDD workflow in R packages or scripts. Provides expert guidance on the red-green-refactor cycle, testthat 3rd edition, snapshot tests, mocking, fixtures, test coverage, and test organization patterns. Triggers: test, testthat, TDD, test-driven, unit test, snapshot test, test coverage, expect_equal, test_that, mock, fixture. Do NOT use for R CMD check or package-level quality gates — use r-package-dev instead. Do NOT use for debugging existing code — use r-debugging instead. Do NOT use for statistical hypothesis testing — use r-stats instead. For a guided Red-Green-Refactor cycle, invoke /r-cmd-tdd-cycle instead.
Write tests first, implement second. TDD for R packages using testthat 3rd edition.
Boundary: Test writing and TDD workflow. For R CMD check and package-level quality gates, use r-package-dev instead.
Agent dispatch: After REFACTOR phase, dispatch to r-code-reviewer for implementation quality. For R CMD check validation, dispatch to r-pkg-check agent.
RED: Write a failing test that defines desired behavior
GREEN: Write minimal implementation to pass the test
REFACTOR: Improve code quality while keeping tests green
Iron law: Never write implementation before its test exists and fails.
RED: Create tests/testthat/test-{feature}.R, write test_that() block, run devtools::test_active_file() — MUST fail. If it passes, the test is wrong.
GREEN: Write minimal code in R/{feature}.R, run devtools::test_active_file() — MUST pass. Do NOT add logic beyond what the test requires.
REFACTOR: Clean up implementation, run devtools::test() — all tests MUST still pass, check coverage with covr::package_coverage() — target 80%+.