How to use R's testthat to unit test individual files?

Viewed 3765

I'm just now getting into unit testing with R and finding it tough sledding so far. What I'd like to do is go into the R console, type test() and have testthat run tests for all the files in my R package.

Here's my environment:

sessionInfo()
R version 3.2.3 (2015-12-10)
Platform: x86_64-apple-darwin15.2.0 (64-bit)
Running under: OS X 10.11.4 (El Capitan)

And directory structure:

math
-- R
------ math.R
------ add.R 
------ subtract.R
-- tests
------ testthat.R 
------ testthat
---------- test_add.R
---------- test_subtract.R
---------- test_math.R

With the following samples of relevant files:

math.R

source('add.R')
source('subtract.R')

doubleAdd <- function(x){
    return(add(x,x) + add(x,x))
}

add.R

add <- function(a,b){
    return(a + b)
}

testthat.R

library(testthat)
library(math)

test_check("math")

test_add.R

context('add tests')

test_that('1 + 1 = 2', {
    expect_equal(2, add(1,1))
})

The Error:

In the R console, I get the following result:

library(devtools)
test()
<b>Loading math
Loading required package: testthat
Error in file(filename, "r", encoding = encoding) (from math.R#1) : 
  cannot open the connection
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
  cannot open file 'add.R': No such file or directory
</b>

However, if I switch the working directory by setwd('R') and run math.R, doubleAdd functions just fine. Also, if I delete math.R or move math.R out of the 'R' directory, test() works just fine.

How am I supposed to setup these files to have test() run tests for all my R files?

1 Answers
Related