rtestthat

testthat in R: sourcing in tested files


I am using the testthat package in R and I am trying to test a function defined in a file example.R. This file contains a call source("../utilities/utilities.R") where utilities.R is a file with functions written by me. However, when I am trying to test a function from example.R, sourcing it within the testing script gives the following error:

Error in file(filename, "r", encoding = encoding) : 
  cannot open the connection
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
  cannot open file '../utilities/utilities.R': No such file or directory

Could you please clarify how to run tests for functions in files that source another file?


Solution

  • 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.