diff --git a/NEWS.md b/NEWS.md index fe9365f5b..d1bbe46fb 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,6 @@ # testthat (development version) +* On CRAN, `test_that()` now automatically skips if a package is not installed (#1585). Practically, this means that you no longer need to check that suggested packages are installed. (We don't do this in the tidyverse because we think it has limited payoff, but other styles advise differently.) * `expect_snapshot()` no longer skips on CRAN, as that skips the rest of the test. Instead it just returns, neither succeeding nor failing (#1585). * Interrupting a test now prints the test name. This makes it easier to tell where a very slow test might be hanging (#1464) * Parallel testthat now does not ignore test files with syntax errors (#1360). diff --git a/R/test-that.R b/R/test-that.R index 63569a44d..e214bd877 100644 --- a/R/test-that.R +++ b/R/test-that.R @@ -173,6 +173,11 @@ test_code <- function(code, env, reporter = NULL, skip_on_empty = TRUE) { } }, expectation = handle_expectation, + packageNotFoundError = function(e) { + if (on_cran()) { + skip(paste0("{", e$package, "} is not installed.")) + } + }, skip = handle_skip, warning = handle_warning, message = handle_message, diff --git a/tests/testthat/test-test-that.R b/tests/testthat/test-test-that.R index 8cb482d2c..486d51e72 100644 --- a/tests/testthat/test-test-that.R +++ b/tests/testthat/test-test-that.R @@ -147,3 +147,20 @@ test_that("no braces required in testthat 2e", { NA ) }) + +test_that("missing packages cause a skip on CRAN", { + local_on_cran(TRUE) + + expectations <- capture_expectations(test_that("", { + library(notinstalled) + })) + expect_length(expectations, 1) + expect_s3_class(expectations[[1]], "expectation_skip") + + local_on_cran(FALSE) + expectations <- capture_expectations(test_that("", { + library(notinstalled) + })) + expect_length(expectations, 1) + expect_s3_class(expectations[[1]], "expectation_error") +})