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?
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.
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()
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With