https://hughjonesd.github.io/doctest/ Skip to contents doctest 0.1.0 * Get started * Reference [ ] * Doctest Documentation examples and tests are similar in some ways: * They are self-contained pieces of code. * They should cover the software's most important functions and typical uses. * They should be simple and clear: complex examples are hard for users to understand, and complex test code can introduce testing bugs. This similarity makes it attractive to use "doctests", which combine tests and documentation. Indeed, several languages, including Python and Rust, have doctests built in.^1 R also checks for errors in examples when running R CMD check. The doctest package extends this idea. It lets you write testthat tests, by adding tags to your roxygen documentation. This helps you check that your examples do what they are supposed to do. Example Here's some roxygen documentation for a function: #' Safe mean #' #' @param x Numeric vector #' @return The mean of `x` #' #' @doctest #' @expect equal(2) #' safe_mean(1:3) #' #' @expect warning("not numeric") #' safe_mean("a") #' #' @expect warning("NA elements") #' safe_mean(c(1, NA)) safe_mean <- function (x) { if (! is.numeric(x)) warning("x is not numeric") if (any(is.na(x))) warning("x contains NA elements") mean(x) } Instead of an @examples section, we have a @doctest section. This will create tests like: # Generated by doctest: do not edit by hand # Please edit file in R/ test_that("Example: safe_mean", { # Created from @doctest for `safe_mean` # Source file: # Source line: 7 expect_equal(safe_mean(1:3), 2) expect_warning(safe_mean("a"), "not numeric") expect_warning(safe_mean(c(1, NA)), "NA elements") }) The .Rd file will be created as normal, with an example section like: \examples{ safe_mean(1:3) safe_mean("a") safe_mean(c(1, NA)) } Usage You can install the development version of doctest like this: devtools::install("hughjonesd/doctest") To use doctest in your package, alter its DESCRIPTION file to add the dt_roclet roclet to roxygen: Roxygen: list(roclets = c("collate", "rd", "namespace", "doctest::dt_roclet")) Add doctest to "Suggests" as a dependency: usethis::use_dev_package("doctest", type = "Suggests", remote = "hughjonesd/doctest") For more information, see the package vignette. Links * Browse source code * Report a bug License * Full license * MIT + file LICENSE Citation * Citing doctest Developers * David Hugh-Jones Author, maintainer Dev status * R-CMD-check * Lifecycle: experimental Developed by David Hugh-Jones. Site built with pkgdown 2.0.6.