Testing R scripts/code outside of package development

You can run testthat tests without package structure, but it is less clean/convenient.

  1. I would put your test files in the same location as if you had already done the package conversion stuff. That means put test files into folder "tests/testthat".

  2. When you run tests on a package in Rstudio, you can just Ctrl-Shift-T, which automatically loads the package and then runs the tests in the appropriate place. If not a package you can do these steps manually:

  • Prior to testing, load the functions you want to test and their dependencies. Source the function files and load packages, either manually or at the top of the test file.
  • Then you can run testthat::test_dir("tests/testthat") which should run all the tests in your testthat directory.

All that said, I have found that it is possible to quickly convert projects into package format with the following:

  • usethis::create_package to give a basic description file, etc
  • Separate out your functions from your scripts. Script files go in a new /scripts directory (or whatever), and functions go in /R.
  • Add all the libraries in your setup.R script as Depends of the package (this is the quick-and-dirty approach -- eventually want to just import the necessary functions from other packages)
9 Likes