I am using the testthat package to test an R package that is within a larger repository. I would like to test the contents of a file outside of the R package.
Can I reference a file that is located outside of an R package while testing?
What I have tried
A reproducible example can be downloaded as MyRepo.tar.gz
My repository is called “myRepo”, and it includes an R package, “myRpkg” and a folder full of miscellaneous scripts
~/MyRepo/
~/MyRepo/MyRpkg
~/MyRepo/Scripts
The tests in “MyRpkg” are in the /tests/ folder
~/myRepo/myRpkg/tests/test.myscript.R
And I want to be able to test a file in the Scripts folder:
~/MyRepo/Scripts/myscript.sh
I would like to read the script to test the contents of the first line doing something like this:
check.script <- readLines("../../../Scripts/myscript.sh")[1]
expect_true(grepl("echo", check.script))
This works fine if I start from the MyRepo directory:
cd ~/MyRepo
R CMD check MyRpkg
But if I move to another directory, it fails:
cd
R CMD check MyRepo/MyRpkg
As it says in R-exts
By default, the check directory is created in the current directory. Thus when running
R CMD checkfrom~/MyRepo, the tests directory is copied to~/MyRepo/MyRpkg.Rcheck/testsand henceis interpreted as
as required. However starting from
~/would implywhich isn’t what you want. A work-around is to specify the directory in which the check directory is created, i.e.
so that the copied
testsdirectory has the same “grandparent” as the originaltestsdirectory.Still, I wonder why the file must be external to the package. If you want to use the file in the package tests, it would make sense to include the file in the package. You could create an inst directory and put the Scripts directory in there, so that the Scripts directory will be copied to the package directory on installation and then
could be used inside the test script, since the package is installed in MyRpkg.Rcheck/foo during R CMD check. Alternatively you could create an exec directory and put the script file in there, then
would work. As both of these solutions only need to find the package installed during testing it wouldn’t matter where you ran R CMD check from. See Package subdirectories and Non-R scripts in packages for more info.