[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M735B0Z59PRCAS96J4G0EG0R":3,"skill-same:01M735B0Z59PRCAS96J4G0EG0R":76},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":33,"commitSha":34,"skillDirectory":35,"forksCount":36,"repositoryHtmlUrl":37,"repositoryHomepageUrl":38,"ownerHtmlUrl":39,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":40,"install":41,"resources":53},"01M735B0Z59PRCAS96J4G0EG0R","testing-r-packages",null,"R package testing best practices with testthat 3+.","Morrison-Lab\u002Fai-config","Morrison-Lab","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F104235520?v=4","01M734G0451S2G35MN4HFQK7XP","Morrison Lab","01M734G059BYFDFQA8YTPDGPMH",4,"MIT","https:\u002F\u002Fgithub.com\u002FMorrison-Lab\u002Fai-config\u002Fblob\u002Fmain\u002Fskills\u002Ftesting-r-packages\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: testing-r-packages\ndescription: R package testing best practices with testthat 3+.\nuser-invocable: true\nallowed-tools:\n  - Read\n  - Edit\n  - Write\n  - Bash\nmetadata:\n  author: Garrick Aden-Buie (@gadenbuie)\n  version: \"1.1\"\nlicense: MIT\n---\n\n# Testing R Packages with testthat\n\nModern best practices for R package testing using testthat 3+.\n\n## Initial Setup\n\nInitialize testing with testthat 3rd edition:\n\n```r\nusethis::use_testthat(3)\n```\n\nThis creates `tests\u002Ftestthat\u002F` directory, adds testthat to `DESCRIPTION` Suggests with `Config\u002Ftestthat\u002Fedition: 3`, and creates `tests\u002Ftestthat.R`.\n\n## File Organization\n\n**Mirror package structure:**\n- Code in `R\u002Ffoofy.R` → tests in `tests\u002Ftestthat\u002Ftest-foofy.R`\n- Use `usethis::use_r(\"foofy\")` and `usethis::use_test(\"foofy\")` to create paired files\n\n**Special files:**\n- `helper-*.R` - Helper functions and custom expectations, sourced before tests\n- `setup-*.R` - Run during `R CMD check` only, not during `load_all()`\n- `fixtures\u002F` - Static test data files accessed via `test_path()`\n\n## Test Structure\n\nTests follow a three-level hierarchy: **File → Test → Expectation**\n\n### Standard Syntax\n\n```r\ntest_that(\"descriptive behavior\", {\n  result \u003C- my_function(input)\n  expect_equal(result, expected_value)\n})\n```\n\n**Test descriptions** should read naturally and describe behavior, not implementation.\n\n### BDD Syntax (describe\u002Fit)\n\nFor behavior-driven development, use `describe()` and `it()`:\n\n```r\ndescribe(\"matrix()\", {\n  it(\"can be multiplied by a scalar\", {\n    m1 \u003C- matrix(1:4, 2, 2)\n    m2 \u003C- m1 * 2\n    expect_equal(matrix(1:4 * 2, 2, 2), m2)\n  })\n\n  it(\"can be transposed\", {\n    m \u003C- matrix(1:4, 2, 2)\n    expect_equal(t(m), matrix(c(1, 3, 2, 4), 2, 2))\n  })\n})\n```\n\n**Key features:**\n- `describe()` groups related specifications for a component\n- `it()` defines individual specifications (like `test_that()`)\n- Supports nesting for hierarchical organization\n- `it()` without code creates pending test placeholders\n\n**Use `describe()` to verify you implement the right things, use `test_that()` to ensure you do things right.**\n\nSee [references\u002Fbdd.md](references\u002Fbdd.md) for comprehensive BDD patterns, nested specifications, and test-first workflows.\n\n## Running Tests\n\nThree scales of testing:\n\n**Micro** (interactive development):\n```r\ndevtools::load_all()\nexpect_equal(foofy(...), expected)\n```\n\n**Mezzo** (single file):\n```r\ntestthat::test_file(\"tests\u002Ftestthat\u002Ftest-foofy.R\")\n# RStudio: Ctrl\u002FCmd + Shift + T\n```\n\n**Macro** (full suite):\n```r\ndevtools::test()    # Ctrl\u002FCmd + Shift + T\ndevtools::check()   # Ctrl\u002FCmd + Shift + E\n```\n\n## Core Expectations\n\n### Equality\n\n```r\nexpect_equal(10, 10 + 1e-7)      # Allows numeric tolerance\nexpect_identical(10L, 10L)       # Exact match required\nexpect_all_equal(x, expected)    # Every element matches (v3.3.0+)\n```\n\n### Errors, Warnings, Messages\n\n```r\nexpect_error(1 \u002F \"a\")\nexpect_error(bad_call(), class = \"specific_error_class\")\nexpect_no_error(valid_call())\n\nexpect_warning(deprecated_func())\nexpect_no_warning(safe_func())\n\nexpect_message(informative_func())\nexpect_no_message(quiet_func())\n```\n\n### Pattern Matching\n\n```r\nexpect_match(\"Testing is fun!\", \"Testing\")\nexpect_match(text, \"pattern\", ignore.case = TRUE)\n```\n\n### Structure and Type\n\n```r\nexpect_length(vector, 10)\nexpect_type(obj, \"list\")\nexpect_s3_class(model, \"lm\")\nexpect_s4_class(obj, \"MyS4Class\")\nexpect_r6_class(obj, \"MyR6Class\")      # v3.3.0+\nexpect_shape(matrix, c(10, 5))         # v3.3.0+\n```\n\n### Sets and Collections\n\n```r\nexpect_setequal(x, y)           # Same elements, any order\nexpect_contains(fruits, \"apple\") # Subset check (v3.2.0+)\nexpect_in(\"apple\", fruits)       # Element in set (v3.2.0+)\nexpect_disjoint(set1, set2)      # No overlap (v3.3.0+)\n```\n\n### Logical\n\n```r\nexpect_true(condition)\nexpect_false(condition)\nexpect_all_true(vector > 0)      # All elements TRUE (v3.3.0+)\nexpect_all_false(vector \u003C 0)     # All elements FALSE (v3.3.0+)\n```\n\n## Design Principles\n\n### 1. Self-Sufficient Tests\n\nEach test should contain all setup, execution, and teardown code:\n\n```r\n# Good: self-contained\ntest_that(\"foofy() works\", {\n  data \u003C- data.frame(x = 1:3, y = letters[1:3])\n  result \u003C- foofy(data)\n  expect_equal(result$x, 1:3)\n})\n\n# Bad: relies on ambient state\ndat \u003C- data.frame(x = 1:3, y = letters[1:3])\ntest_that(\"foofy() works\", {\n  result \u003C- foofy(dat)  # Where did 'dat' come from?\n  expect_equal(result$x, 1:3)\n})\n```\n\n### 2. Self-Contained Tests (Cleanup Side Effects)\n\nUse `withr` to manage state changes:\n\n```r\ntest_that(\"function respects options\", {\n  withr::local_options(my_option = \"test_value\")\n  withr::local_envvar(MY_VAR = \"test\")\n  withr::local_package(\"jsonlite\")\n\n  result \u003C- my_function()\n  expect_equal(result$setting, \"test_value\")\n  # Automatic cleanup after test\n})\n```\n\n**Common withr functions:**\n- `local_options()` - Temporarily set options\n- `local_envvar()` - Temporarily set environment variables\n- `local_tempfile()` - Create temp file with automatic cleanup\n- `local_tempdir()` - Create temp directory with automatic cleanup\n- `local_package()` - Temporarily attach package\n\n### 3. Plan for Test Failure\n\nWrite tests assuming they will fail and need debugging:\n- Tests should run independently in fresh R sessions\n- Avoid hidden dependencies on earlier tests\n- Make test logic explicit and obvious\n\n### 4. Repetition is Acceptable\n\nRepeat setup code in tests rather than factoring it out.\nTest clarity is more important than avoiding duplication.\n\n### 5. Use `devtools::load_all()` Workflow\n\nDuring development:\n- Use `devtools::load_all()` instead of `library()`\n- Makes all functions available (including unexported)\n- Automatically attaches testthat\n- Eliminates need for `library()` calls in tests\n\n## Snapshot Testing\n\nFor complex output that's difficult to verify programmatically, use snapshot tests.\nSee [references\u002Fsnapshots.md](references\u002Fsnapshots.md) for complete guide.\n\n**Basic pattern:**\n\n```r\ntest_that(\"error message is helpful\", {\n  expect_snapshot(\n    error = TRUE,\n    validate_input(NULL)\n  )\n})\n```\n\nSnapshots stored in `tests\u002Ftestthat\u002F_snaps\u002F`.\n\n**Workflow:**\n```r\ndevtools::test()                    # Creates new snapshots\ntestthat::snapshot_review('name')   # Review changes\ntestthat::snapshot_accept('name')   # Accept changes\n```\n\n## Test Fixtures and Data\n\nThree approaches for test data:\n\n**1.\nConstructor functions** - Create data on-demand:\n```r\nnew_sample_data \u003C- function(n = 10) {\n  data.frame(id = seq_len(n), value = rnorm(n))\n}\n```\n\n**2.\nLocal functions with cleanup** - Handle side effects:\n```r\nlocal_temp_csv \u003C- function(data, env = parent.frame()) {\n  path \u003C- withr::local_tempfile(fileext = \".csv\", .local_envir = env)\n  write.csv(data, path, row.names = FALSE)\n  path\n}\n```\n\n**3.\nStatic fixture files** - Store in `fixtures\u002F` directory:\n```r\ndata \u003C- readRDS(test_path(\"fixtures\", \"sample_data.rds\"))\n```\n\nSee [references\u002Ffixtures.md](references\u002Ffixtures.md) for detailed fixture patterns.\n\n## Mocking\n\nReplace external dependencies during testing using `local_mocked_bindings()`.\nSee [references\u002Fmocking.md](references\u002Fmocking.md) for comprehensive mocking strategies.\n\n**Basic pattern:**\n\n```r\ntest_that(\"function works with mocked dependency\", {\n  local_mocked_bindings(\n    external_api = function(...) list(status = \"success\", data = \"mocked\")\n  )\n\n  result \u003C- my_function_that_calls_api()\n  expect_equal(result$status, \"success\")\n})\n```\n\n## Common Patterns\n\n### Testing Errors with Specific Classes\n\n```r\ntest_that(\"validation catches errors\", {\n  expect_error(\n    validate_input(\"wrong_type\"),\n    class = \"vctrs_error_cast\"\n  )\n})\n```\n\n### Testing with Temporary Files\n\n```r\ntest_that(\"file processing works\", {\n  temp_file \u003C- withr::local_tempfile(\n    lines = c(\"line1\", \"line2\", \"line3\")\n  )\n\n  result \u003C- process_file(temp_file)\n  expect_equal(length(result), 3)\n})\n```\n\n### Testing with Modified Options\n\n```r\ntest_that(\"output respects width\", {\n  withr::local_options(width = 40)\n\n  output \u003C- capture_output(print(my_object))\n  expect_lte(max(nchar(strsplit(output, \"\\n\")[[1]])), 40)\n})\n```\n\n### Testing Multiple Related Cases\n\n```r\ntest_that(\"str_trunc() handles all directions\", {\n  trunc \u003C- function(direction) {\n    str_trunc(\"This string is moderately long\", direction, width = 20)\n  }\n\n  expect_equal(trunc(\"right\"), \"This string is mo...\")\n  expect_equal(trunc(\"left\"), \"...erately long\")\n  expect_equal(trunc(\"center\"), \"This stri...ely long\")\n})\n```\n\n### Custom Expectations in Helper Files\n\n```r\n# In tests\u002Ftestthat\u002Fhelper-expectations.R\nexpect_valid_user \u003C- function(user) {\n  expect_type(user, \"list\")\n  expect_named(user, c(\"id\", \"name\", \"email\"))\n  expect_type(user$id, \"integer\")\n  expect_match(user$email, \"@\")\n}\n\n# In test file\ntest_that(\"user creation works\", {\n  user \u003C- create_user(\"test@example.com\")\n  expect_valid_user(user)\n})\n```\n\n## File System Discipline\n\n**Always write to temp directory:**\n\n```r\n# Good\noutput \u003C- withr::local_tempfile(fileext = \".csv\")\nwrite.csv(data, output)\n\n# Bad - writes to package directory\nwrite.csv(data, \"output.csv\")\n```\n\n**Access test fixtures with `test_path()`:**\n\n```r\n# Good - works in all contexts\ndata \u003C- readRDS(test_path(\"fixtures\", \"data.rds\"))\n\n# Bad - relative paths break\ndata \u003C- readRDS(\"fixtures\u002Fdata.rds\")\n```\n\n## Advanced Topics\n\nFor advanced testing scenarios, see:\n\n- **[references\u002Fbdd.md](references\u002Fbdd.md)** - BDD-style testing with describe\u002Fit, nested specifications, test-first workflows\n- **[references\u002Fsnapshots.md](references\u002Fsnapshots.md)** - Snapshot testing, transforms, variants\n- **[references\u002Fmocking.md](references\u002Fmocking.md)** - Mocking strategies, webfakes, httptest2\n- **[references\u002Ffixtures.md](references\u002Ffixtures.md)** - Fixture patterns, database fixtures, helper files\n- **[references\u002Fadvanced.md](references\u002Fadvanced.md)** - Skipping tests, secrets management, CRAN requirements, custom expectations, parallel testing\n\n## testthat 3 Modernizations\n\nWhen working with testthat 3 code, prefer modern patterns:\n\n**Deprecated → Modern:**\n- `context()` → Remove (duplicates filename)\n- `expect_equivalent()` → `expect_equal(ignore_attr = TRUE)`\n- `with_mock()` → `local_mocked_bindings()`\n- `is_null()`, `is_true()`, `is_false()` → `expect_null()`, `expect_true()`, `expect_false()`\n\n**New in testthat 3:**\n- Edition system (`Config\u002Ftestthat\u002Fedition: 3`)\n- Improved snapshot testing\n- `waldo::compare()` for better diff output\n- Unified condition handling\n- `local_mocked_bindings()` works with byte-compiled code\n- Parallel test execution support\n\n## Quick Reference\n\n**Initialize:** `usethis::use_testthat(3)`\n\n**Run tests:** `devtools::test()` or Ctrl\u002FCmd + Shift + T\n\n**Create test file:** `usethis::use_test(\"name\")`\n\n**Review snapshots:** `testthat::snapshot_review()`\n\n**Accept snapshots:** `testthat::snapshot_accept()`\n\n**Find slow tests:** `devtools::test(reporter = \"slow\")`\n\n**Shuffle tests:** `devtools::test(shuffle = TRUE)`\n\n## Relationship to other skills\n\nThis is the general testthat reference: fixtures, mocking, snapshots, BDD-style tests, and the full expectation API, including `expect_error()`\u002F`expect_warning()`.\n[`r-package-development`](..\u002Fr-package-development\u002FSKILL.md) has a narrower, author-specific preference for snapshot-testing errors and warnings instead.\nMatch the package's existing `expect_error()`\u002F`expect_warning()` or snapshot-testing style where precedent exists.\nOn a fresh package with no precedent, follow this skill's preference for snapshot-based error\u002Fwarning tests.\nNeither skill covers `R CMD check` output ([`r-pkg-check`](..\u002Fr-pkg-check\u002FSKILL.md)) or CRAN submission ([`r-pkg-cran-checklist`](..\u002Fr-pkg-cran-checklist\u002FSKILL.md)).\n","# Testing R Packages with testthat\n\nModern best practices for R package testing using testthat 3+.\n\n## Initial Setup\n\nInitialize testing with testthat 3rd edition:\n\n```r\nusethis::use_testthat(3)\n```\n\nThis creates `tests\u002Ftestthat\u002F` directory, adds testthat to `DESCRIPTION` Suggests with `Config\u002Ftestthat\u002Fedition: 3`, and creates `tests\u002Ftestthat.R`.\n\n## File Organization\n\n**Mirror package structure:**\n- Code in `R\u002Ffoofy.R` → tests in `tests\u002Ftestthat\u002Ftest-foofy.R`\n- Use `usethis::use_r(\"foofy\")` and `usethis::use_test(\"foofy\")` to create paired files\n\n**Special files:**\n- `helper-*.R` - Helper functions and custom expectations, sourced before tests\n- `setup-*.R` - Run during `R CMD check` only, not during `load_all()`\n- `fixtures\u002F` - Static test data files accessed via `test_path()`\n\n## Test Structure\n\nTests follow a three-level hierarchy: **File → Test → Expectation**\n\n### Standard Syntax\n\n```r\ntest_that(\"descriptive behavior\", {\n  result \u003C- my_function(input)\n  expect_equal(result, expected_value)\n})\n```\n\n**Test descriptions** should read naturally and describe behavior, not implementation.\n\n### BDD Syntax (describe\u002Fit)\n\nFor behavior-driven development, use `describe()` and `it()`:\n\n```r\ndescribe(\"matrix()\", {\n  it(\"can be multiplied by a scalar\", {\n    m1 \u003C- matrix(1:4, 2, 2)\n    m2 \u003C- m1 * 2\n    expect_equal(matrix(1:4 * 2, 2, 2), m2)\n  })\n\n  it(\"can be transposed\", {\n    m \u003C- matrix(1:4, 2, 2)\n    expect_equal(t(m), matrix(c(1, 3, 2, 4), 2, 2))\n  })\n})\n```\n\n**Key features:**\n- `describe()` groups related specifications for a component\n- `it()` defines individual specifications (like `test_that()`)\n- Supports nesting for hierarchical organization\n- `it()` without code creates pending test placeholders\n\n**Use `describe()` to verify you implement the right things, use `test_that()` to ensure you do things right.**\n\nSee [references\u002Fbdd.md](references\u002Fbdd.md) for comprehensive BDD patterns, nested specifications, and test-first workflows.\n\n## Running Tests\n\nThree scales of testing:\n\n**Micro** (interactive development):\n```r\ndevtools::load_all()\nexpect_equal(foofy(...), expected)\n```\n\n**Mezzo** (single file):\n```r\ntestthat::test_file(\"tests\u002Ftestthat\u002Ftest-foofy.R\")\n# RStudio: Ctrl\u002FCmd + Shift + T\n```\n\n**Macro** (full suite):\n```r\ndevtools::test()    # Ctrl\u002FCmd + Shift + T\ndevtools::check()   # Ctrl\u002FCmd + Shift + E\n```\n\n## Core Expectations\n\n### Equality\n\n```r\nexpect_equal(10, 10 + 1e-7)      # Allows numeric tolerance\nexpect_identical(10L, 10L)       # Exact match required\nexpect_all_equal(x, expected)    # Every element matches (v3.3.0+)\n```\n\n### Errors, Warnings, Messages\n\n```r\nexpect_error(1 \u002F \"a\")\nexpect_error(bad_call(), class = \"specific_error_class\")\nexpect_no_error(valid_call())\n\nexpect_warning(deprecated_func())\nexpect_no_warning(safe_func())\n\nexpect_message(informative_func())\nexpect_no_message(quiet_func())\n```\n\n### Pattern Matching\n\n```r\nexpect_match(\"Testing is fun!\", \"Testing\")\nexpect_match(text, \"pattern\", ignore.case = TRUE)\n```\n\n### Structure and Type\n\n```r\nexpect_length(vector, 10)\nexpect_type(obj, \"list\")\nexpect_s3_class(model, \"lm\")\nexpect_s4_class(obj, \"MyS4Class\")\nexpect_r6_class(obj, \"MyR6Class\")      # v3.3.0+\nexpect_shape(matrix, c(10, 5))         # v3.3.0+\n```\n\n### Sets and Collections\n\n```r\nexpect_setequal(x, y)           # Same elements, any order\nexpect_contains(fruits, \"apple\") # Subset check (v3.2.0+)\nexpect_in(\"apple\", fruits)       # Element in set (v3.2.0+)\nexpect_disjoint(set1, set2)      # No overlap (v3.3.0+)\n```\n\n### Logical\n\n```r\nexpect_true(condition)\nexpect_false(condition)\nexpect_all_true(vector > 0)      # All elements TRUE (v3.3.0+)\nexpect_all_false(vector \u003C 0)     # All elements FALSE (v3.3.0+)\n```\n\n## Design Principles\n\n### 1. Self-Sufficient Tests\n\nEach test should contain all setup, execution, and teardown code:\n\n```r\n# Good: self-contained\ntest_that(\"foofy() works\", {\n  data \u003C- data.frame(x = 1:3, y = letters[1:3])\n  result \u003C- foofy(data)\n  expect_equal(result$x, 1:3)\n})\n\n# Bad: relies on ambient state\ndat \u003C- data.frame(x = 1:3, y = letters[1:3])\ntest_that(\"foofy() works\", {\n  result \u003C- foofy(dat)  # Where did 'dat' come from?\n  expect_equal(result$x, 1:3)\n})\n```\n\n### 2. Self-Contained Tests (Cleanup Side Effects)\n\nUse `withr` to manage state changes:\n\n```r\ntest_that(\"function respects options\", {\n  withr::local_options(my_option = \"test_value\")\n  withr::local_envvar(MY_VAR = \"test\")\n  withr::local_package(\"jsonlite\")\n\n  result \u003C- my_function()\n  expect_equal(result$setting, \"test_value\")\n  # Automatic cleanup after test\n})\n```\n\n**Common withr functions:**\n- `local_options()` - Temporarily set options\n- `local_envvar()` - Temporarily set environment variables\n- `local_tempfile()` - Create temp file with automatic cleanup\n- `local_tempdir()` - Create temp directory with automatic cleanup\n- `local_package()` - Temporarily attach package\n\n### 3. Plan for Test Failure\n\nWrite tests assuming they will fail and need debugging:\n- Tests should run independently in fresh R sessions\n- Avoid hidden dependencies on earlier tests\n- Make test logic explicit and obvious\n\n### 4. Repetition is Acceptable\n\nRepeat setup code in tests rather than factoring it out.\nTest clarity is more important than avoiding duplication.\n\n### 5. Use `devtools::load_all()` Workflow\n\nDuring development:\n- Use `devtools::load_all()` instead of `library()`\n- Makes all functions available (including unexported)\n- Automatically attaches testthat\n- Eliminates need for `library()` calls in tests\n\n## Snapshot Testing\n\nFor complex output that's difficult to verify programmatically, use snapshot tests.\nSee [references\u002Fsnapshots.md](references\u002Fsnapshots.md) for complete guide.\n\n**Basic pattern:**\n\n```r\ntest_that(\"error message is helpful\", {\n  expect_snapshot(\n    error = TRUE,\n    validate_input(NULL)\n  )\n})\n```\n\nSnapshots stored in `tests\u002Ftestthat\u002F_snaps\u002F`.\n\n**Workflow:**\n```r\ndevtools::test()                    # Creates new snapshots\ntestthat::snapshot_review('name')   # Review changes\ntestthat::snapshot_accept('name')   # Accept changes\n```\n\n## Test Fixtures and Data\n\nThree approaches for test data:\n\n**1.\nConstructor functions** - Create data on-demand:\n```r\nnew_sample_data \u003C- function(n = 10) {\n  data.frame(id = seq_len(n), value = rnorm(n))\n}\n```\n\n**2.\nLocal functions with cleanup** - Handle side effects:\n```r\nlocal_temp_csv \u003C- function(data, env = parent.frame()) {\n  path \u003C- withr::local_tempfile(fileext = \".csv\", .local_envir = env)\n  write.csv(data, path, row.names = FALSE)\n  path\n}\n```\n\n**3.\nStatic fixture files** - Store in `fixtures\u002F` directory:\n```r\ndata \u003C- readRDS(test_path(\"fixtures\", \"sample_data.rds\"))\n```\n\nSee [references\u002Ffixtures.md](references\u002Ffixtures.md) for detailed fixture patterns.\n\n## Mocking\n\nReplace external dependencies during testing using `local_mocked_bindings()`.\nSee [references\u002Fmocking.md](references\u002Fmocking.md) for comprehensive mocking strategies.\n\n**Basic pattern:**\n\n```r\ntest_that(\"function works with mocked dependency\", {\n  local_mocked_bindings(\n    external_api = function(...) list(status = \"success\", data = \"mocked\")\n  )\n\n  result \u003C- my_function_that_calls_api()\n  expect_equal(result$status, \"success\")\n})\n```\n\n## Common Patterns\n\n### Testing Errors with Specific Classes\n\n```r\ntest_that(\"validation catches errors\", {\n  expect_error(\n    validate_input(\"wrong_type\"),\n    class = \"vctrs_error_cast\"\n  )\n})\n```\n\n### Testing with Temporary Files\n\n```r\ntest_that(\"file processing works\", {\n  temp_file \u003C- withr::local_tempfile(\n    lines = c(\"line1\", \"line2\", \"line3\")\n  )\n\n  result \u003C- process_file(temp_file)\n  expect_equal(length(result), 3)\n})\n```\n\n### Testing with Modified Options\n\n```r\ntest_that(\"output respects width\", {\n  withr::local_options(width = 40)\n\n  output \u003C- capture_output(print(my_object))\n  expect_lte(max(nchar(strsplit(output, \"\\n\")[[1]])), 40)\n})\n```\n\n### Testing Multiple Related Cases\n\n```r\ntest_that(\"str_trunc() handles all directions\", {\n  trunc \u003C- function(direction) {\n    str_trunc(\"This string is moderately long\", direction, width = 20)\n  }\n\n  expect_equal(trunc(\"right\"), \"This string is mo...\")\n  expect_equal(trunc(\"left\"), \"...erately long\")\n  expect_equal(trunc(\"center\"), \"This stri...ely long\")\n})\n```\n\n### Custom Expectations in Helper Files\n\n```r\n# In tests\u002Ftestthat\u002Fhelper-expectations.R\nexpect_valid_user \u003C- function(user) {\n  expect_type(user, \"list\")\n  expect_named(user, c(\"id\", \"name\", \"email\"))\n  expect_type(user$id, \"integer\")\n  expect_match(user$email, \"@\")\n}\n\n# In test file\ntest_that(\"user creation works\", {\n  user \u003C- create_user(\"test@example.com\")\n  expect_valid_user(user)\n})\n```\n\n## File System Discipline\n\n**Always write to temp directory:**\n\n```r\n# Good\noutput \u003C- withr::local_tempfile(fileext = \".csv\")\nwrite.csv(data, output)\n\n# Bad - writes to package directory\nwrite.csv(data, \"output.csv\")\n```\n\n**Access test fixtures with `test_path()`:**\n\n```r\n# Good - works in all contexts\ndata \u003C- readRDS(test_path(\"fixtures\", \"data.rds\"))\n\n# Bad - relative paths break\ndata \u003C- readRDS(\"fixtures\u002Fdata.rds\")\n```\n\n## Advanced Topics\n\nFor advanced testing scenarios, see:\n\n- **[references\u002Fbdd.md](references\u002Fbdd.md)** - BDD-style testing with describe\u002Fit, nested specifications, test-first workflows\n- **[references\u002Fsnapshots.md](references\u002Fsnapshots.md)** - Snapshot testing, transforms, variants\n- **[references\u002Fmocking.md](references\u002Fmocking.md)** - Mocking strategies, webfakes, httptest2\n- **[references\u002Ffixtures.md](references\u002Ffixtures.md)** - Fixture patterns, database fixtures, helper files\n- **[references\u002Fadvanced.md](references\u002Fadvanced.md)** - Skipping tests, secrets management, CRAN requirements, custom expectations, parallel testing\n\n## testthat 3 Modernizations\n\nWhen working with testthat 3 code, prefer modern patterns:\n\n**Deprecated → Modern:**\n- `context()` → Remove (duplicates filename)\n- `expect_equivalent()` → `expect_equal(ignore_attr = TRUE)`\n- `with_mock()` → `local_mocked_bindings()`\n- `is_null()`, `is_true()`, `is_false()` → `expect_null()`, `expect_true()`, `expect_false()`\n\n**New in testthat 3:**\n- Edition system (`Config\u002Ftestthat\u002Fedition: 3`)\n- Improved snapshot testing\n- `waldo::compare()` for better diff output\n- Unified condition handling\n- `local_mocked_bindings()` works with byte-compiled code\n- Parallel test execution support\n\n## Quick Reference\n\n**Initialize:** `usethis::use_testthat(3)`\n\n**Run tests:** `devtools::test()` or Ctrl\u002FCmd + Shift + T\n\n**Create test file:** `usethis::use_test(\"name\")`\n\n**Review snapshots:** `testthat::snapshot_review()`\n\n**Accept snapshots:** `testthat::snapshot_accept()`\n\n**Find slow tests:** `devtools::test(reporter = \"slow\")`\n\n**Shuffle tests:** `devtools::test(shuffle = TRUE)`\n\n## Relationship to other skills\n\nThis is the general testthat reference: fixtures, mocking, snapshots, BDD-style tests, and the full expectation API, including `expect_error()`\u002F`expect_warning()`.\n[`r-package-development`](..\u002Fr-package-development\u002FSKILL.md) has a narrower, author-specific preference for snapshot-testing errors and warnings instead.\nMatch the package's existing `expect_error()`\u002F`expect_warning()` or snapshot-testing style where precedent exists.\nOn a fresh package with no precedent, follow this skill's preference for snapshot-based error\u002Fwarning tests.\nNeither skill covers `R CMD check` output ([`r-pkg-check`](..\u002Fr-pkg-check\u002FSKILL.md)) or CRAN submission ([`r-pkg-cran-checklist`](..\u002Fr-pkg-cran-checklist\u002FSKILL.md)).\n",{"name":5,"license":15,"metadata":24,"description":7,"allowed-tools":27,"user-invocable":32},{"author":25,"version":26},"Garrick Aden-Buie (@gadenbuie)","1.1",[28,29,30,31],"Read","Edit","Write","Bash",true,"main","0f720481f8ce3b3d9fef485f6e230d8b3035748e","skills\u002Ftesting-r-packages",1,"https:\u002F\u002Fgithub.com\u002FMorrison-Lab\u002Fai-config","https:\u002F\u002Fmorrison-lab.github.io\u002Fai-config\u002F","https:\u002F\u002Fgithub.com\u002FMorrison-Lab","2026-11-15 04:39:15",{"source":8,"skillName":5,"commands":42,"prompt":52,"zipAvailable":32},[43,46,49],{"tool":44,"command":45},"npx","npx skills add Morrison-Lab\u002Fai-config --skill testing-r-packages",{"tool":47,"command":48},"bunx","bunx skills add Morrison-Lab\u002Fai-config --skill testing-r-packages",{"tool":50,"command":51},"pnpm","pnpm dlx skills add Morrison-Lab\u002Fai-config --skill testing-r-packages","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMorrison-Lab\u002Fai-config\u002Fblob\u002Fmain\u002Fskills\u002Ftesting-r-packages\u002FSKILL.md",[54,60,64,68,72],{"path":55,"resourceType":56,"resourceTypeDesc":57,"sizeBytes":58,"sourceHtmlUrl":59},"references\u002Fadvanced.md","REFERENCE","参考文档",8068,"https:\u002F\u002Fgithub.com\u002FMorrison-Lab\u002Fai-config\u002Fblob\u002Fmain\u002Fskills\u002Ftesting-r-packages\u002Freferences\u002Fadvanced.md",{"path":61,"resourceType":56,"resourceTypeDesc":57,"sizeBytes":62,"sourceHtmlUrl":63},"references\u002Fbdd.md",10626,"https:\u002F\u002Fgithub.com\u002FMorrison-Lab\u002Fai-config\u002Fblob\u002Fmain\u002Fskills\u002Ftesting-r-packages\u002Freferences\u002Fbdd.md",{"path":65,"resourceType":56,"resourceTypeDesc":57,"sizeBytes":66,"sourceHtmlUrl":67},"references\u002Ffixtures.md",7570,"https:\u002F\u002Fgithub.com\u002FMorrison-Lab\u002Fai-config\u002Fblob\u002Fmain\u002Fskills\u002Ftesting-r-packages\u002Freferences\u002Ffixtures.md",{"path":69,"resourceType":56,"resourceTypeDesc":57,"sizeBytes":70,"sourceHtmlUrl":71},"references\u002Fmocking.md",5206,"https:\u002F\u002Fgithub.com\u002FMorrison-Lab\u002Fai-config\u002Fblob\u002Fmain\u002Fskills\u002Ftesting-r-packages\u002Freferences\u002Fmocking.md",{"path":73,"resourceType":56,"resourceTypeDesc":57,"sizeBytes":74,"sourceHtmlUrl":75},"references\u002Fsnapshots.md",3723,"https:\u002F\u002Fgithub.com\u002FMorrison-Lab\u002Fai-config\u002Fblob\u002Fmain\u002Fskills\u002Ftesting-r-packages\u002Freferences\u002Fsnapshots.md",[77,84,91,98,105,112],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M735BVYCGR5VEC65AFDVSNKW","wrap-up","End-of-session verification and UMS.","https:\u002F\u002Fgithub.com\u002FMorrison-Lab\u002Fai-config\u002Fblob\u002Fmain\u002Fskills\u002Fwrap-up\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M735BTH469T1CQ8G2Q9GENCR","workaround-watcher","Watch upstream issue for fix.","https:\u002F\u002Fgithub.com\u002FMorrison-Lab\u002Fai-config\u002Fblob\u002Fmain\u002Fskills\u002Fworkaround-watcher\u002FSKILL.md",[],[],{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":19},"01M735BRKZWFANSQ0GM380B4TD","wn","→ whats-next.","https:\u002F\u002Fgithub.com\u002FMorrison-Lab\u002Fai-config\u002Fblob\u002Fmain\u002Fskills\u002Fwn\u002FSKILL.md",[],[],{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":19},"01M735BPE9V830B3B6NGXQ56J6","whats-next","Recommend concrete next step or action.","https:\u002F\u002Fgithub.com\u002FMorrison-Lab\u002Fai-config\u002Fblob\u002Fmain\u002Fskills\u002Fwhats-next\u002FSKILL.md",[],[],{"skillNo":106,"name":107,"nameZh":6,"description":108,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":109,"categories":110,"keywords":111,"publishedAt":19},"01M735BMHQ60EAD5B7QAWXC5A0","wait-for-results","Wait for pipeline\u002FCI results.","https:\u002F\u002Fgithub.com\u002FMorrison-Lab\u002Fai-config\u002Fblob\u002Fmain\u002Fskills\u002Fwait-for-results\u002FSKILL.md",[],[],{"skillNo":113,"name":114,"nameZh":6,"description":115,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":116,"categories":117,"keywords":118,"publishedAt":19},"01M735BKGZHPN1PEMJ7YBD5VJ8","wai","→ send-notes.","https:\u002F\u002Fgithub.com\u002FMorrison-Lab\u002Fai-config\u002Fblob\u002Fmain\u002Fskills\u002Fwai\u002FSKILL.md",[],[]]