25

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?

janosdivenyi
  • 3,136
  • 2
  • 24
  • 36
paljenczy
  • 4,779
  • 8
  • 33
  • 46

4 Answers4

16

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.

user3137190
  • 318
  • 3
  • 8
  • Since my tests, data, and functions are all in separate folders, I found that I needed to assign the working directory as such wd <- file.path(getwd(),'..') and then specify a functions_dir <- file.path(wd,'functions') and data_dir <- file.path(wd, 'data') inside a helper file. Each test file will then have access to those variables to source their functions and data. – Todd Jul 18 '15 at 13:49
10

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()).

hplieninger
  • 3,214
  • 27
  • 32
0

No great solution to this problem I've found, so far mine has been to set the working directory within each test using the package here.

test_that('working directory is set',{
  setwd(here())
  # test code here
})
Kyouma
  • 320
  • 6
  • 14
-1

I put the source("C:/Users/.../Utilities.R") in the test file.

Philip
  • 638
  • 1
  • 8
  • 22