5

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?

bright-star
  • 6,016
  • 6
  • 42
  • 81
  • 2
    Take a look at some of the more advanced use of **knitr**. `purl` will take care of point (1) and you can use [code externalization](http://yihui.name/knitr/demo/externalization/) to deal with (2) and (3). – Thomas Nov 05 '13 at 23:47
  • 2
    I think you could use testthat http://cran.r-project.org/web/packages/testthat/index.html – sckott Nov 06 '13 at 00:02
  • You might also be able to automatically generate a markdown/HTML file with the results of your tests. – Ramnath Nov 06 '13 at 00:23

1 Answers1

8

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.

sckott
  • 5,755
  • 2
  • 26
  • 42
  • 1
    You could also save the results of the test, and then have the later code chunks only include / evaluated when all the tests are passed. – mnel Nov 06 '13 at 02:00
  • 1
    That worked. echo=FALSE, eval=FALSE in the code snippet label allows me to control if tests appear in the knitted output. – bright-star Nov 06 '13 at 06:57