testthat in R: sourcing in tested files

testthat allows you to define and source helper files (see ?source_test_helpers):

Helper scripts are R scripts accompanying test scripts but prefixed by helper. These scripts are run once before the tests are run.

So what worked perfectly for me is simply putting a file "helper-functions.R" containing the code that I want to source in "/tests/testthat/". You don't have to call source_test_helpers() yourself, testthat will automatically do that when you run tests (e.g., via devtools::test() or testthat::test_dir()).


Might be a bit late, but I found a solution. Test_that sets the directory holding the test file as the current working directory. See the code below from test-files.r. This causes the working directory to be /tests. Therefore, your main scripts need to source ("../file.R"), which works for testing, but not for running your app.

https://github.com/hadley/testthat/blob/master/R/test-files.r

source_dir <- function(path, pattern = "\\.[rR]$", env = test_env(),
                       chdir = TRUE) {
  files <- normalizePath(sort(dir(path, pattern, full.names = TRUE)))
  if (chdir) {
    old <- setwd(path)
    on.exit(setwd(old))
  }

The solution I found was to add setwd("..") in my test files and simply source the file name without the path. source("file.R") instead of source("../file.R"). Seems to work for me.

Tags:

R

Testthat