Let's say I have a function, documented with an example (using roxygen):
#' @title Add two numbers
#' @param x a scalar
#' @param y a scalar
#' @examples
#' testobj <- add(x + y)
add <- function(x, y) {
return(x+y)
}
Now I also want to run some tests on the resulting object, to make sure the function does as it should.
I'll use testthat
for that:
context("Adding stuff")
testobj <- add(x, y) # THIS is the duplicate line that bothers me.
test_that(desc = "Additions work", code = {
testthat::expect_length(object = x, n = 1)
})
How can I reuse the testobj
created in the example and then run some tests on it in testthat
?
It's trivial in this case, but it leads to substantial duplication if the function is more complex.
Or am I using this wrong?
You can use the
example
function exported fromutils
to run the examples contained in the documentation of a function.Note that it is recommended to use concrete examples in your roxygen comments:
Instead of
Use