Question

I'm learning to do my first unit tests with R, and I write my code in R Markdown files to make delivering short research reports easy. At the same time, I would like to test the functions I use in these files to make sure the results are sane.

Here's the problem: R Markdown files are meant to go into HTML weavers, not the RUnit test harness. If I want to load a function into the test code, I have a few choices:

  1. Copy-paste the code chunk from the Markdown file, which decouples the code in the Markdown doc from the tested code
  2. Put my test code inside the Markdown file, which makes the report difficult to understand (perhaps at the end would be tolerable)
  3. Write the code, test it first, and then include it as a library in the Markdown code, which takes away the informative character of having the code in the body of the report

Is there a more sensible way to go about this that avoids the disadvantages of each of these approaches?

Was it helpful?

Solution

You could do something like this

## Rmarkdown file with tests

```{r definefxn}
foo <- function(x) x^2
```

Test fxn

```{r testfxn}
library(testthat)

expect_is(foo(8), "numeric")
expect_equal(foo(8), 6)
```

Where of course the tests that pass don't print anything, but the tests that fail print meaningful messages about what failed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top