有一种方法,但它并不像你想要的那样顺利。您必须在块testthat
内调用函数。@examples
这是一个示例函数:
#' @examples
#' testStrings <- c("1234567890",
#' "123 456 7890")
#'
#' testthat::expect_equal(extractPhoneNumbers(testStrings), "0123")
extractPhoneNumbers <- function(inputStr) {
# check input:
if (!is.character(inputStr)) {
stop("'inputStr' must be a (vector of) string(s)!")
}
# imports
`%>%` <- stringr::`%>%`
replace_all <- stringr::str_replace_all
extract_all <- stringr::str_extract_all
# intermediary regex's
visualDelimitersRegex <- "[()+\\-_. ]"
phoneNumberRegex <- "[:digit:]{10}"
inputStr %>%
replace_all(pattern = visualDelimitersRegex, replacement = "") %>%
extract_all(pattern = phoneNumberRegex)
}
当你运行devtools::run_examples()
ordevtools::check
时,两者都会抛出错误,因为调用会testthat::expect_equal()
抛出错误。
示例输出devtools::check
看起来像
*** SNIP ***
* checking for unstated dependencies in examples ... OK
* checking examples ... ERROR
Running examples in ‘demoPkg-Ex.R’ failed
The error most likely occurred in:
> base::assign(".ptime", proc.time(), pos = "CheckExEnv")
> ### Name: extractPhoneNumbers
> ### Title: Extract Phone Numbers
> ### Aliases: extractPhoneNumbers
>
> ### ** Examples
>
> testStrings <- c("1234567890",
+ "123 456 7890")
>
> testthat::expect_equal(extractPhoneNumbers(testStrings), "0123")
Error: extractPhoneNumbers(testStrings) not equal to "0123"
Modes: list, character
Length mismatch: comparison on first 1 components
Component 1: 1 string mismatch
Execution halted
* checking for unstated dependencies in ‘tests’ ... OK
* checking tests ...
Running ‘testthat.R’
OK
* checking PDF version of manual ... OK
* DONE
Status: 1 ERROR