Reputation: 5206
I am looking for best practice help with the brilliant testthat
. Where is the best place to put your library(xyzpackage)
calls to use all the package functionality?
I first have been setting up a runtest.R
setting up paths and packages.
I then run test_files(test-code.R)
which only holds context and tests. Example for structure follows:
# runtests.R
library(testthat)
library(data.table)
source("code/plotdata-fun.R")
mytestreport <- test_file("code/test-plotdata.R")
# does other stuff like append date and log test report (not shown)
and in my test files e.g. test-plotdata.R
(a stripped down version):
#my tests for plotdata
context("Plot Chart")
test_that("Inputs valid", {
test.dt = data.table(px = c(1,2,3), py = c(1,4,9))
test.notdt <- c(1,2,3)
# illustrating the check for data table as first param in my code
expect_error(PlotMyStandardChart(test.notdt,
plot.me = FALSE),
"Argument must be data table/frame")
# then do other tests with test.dt etc...
})
Is this the way @hadley intended it to be used? It is not clear from the journal article. Should I also be duplicating library calls in my test files as well? Do you need a library set up in each context, or just one at start of file?
Is it okay to over-call library(package) in r?
To use the test_dir()
and other functionality what is best way to set up your files. I do use require() in my functions, but I also set up test data examples in the contexts. (In above example, you will see I would need data.table package for test.dt to use in other tests).
Thanks for your help.
Upvotes: 11
Views: 2109
Reputation:
If you use devtools::test(filter="mytestfile")
then devtools will take care of calling helper files etc. for you. In this way you don't need to do anything special to make your test file work on its own. Basically, this is just the same as if you ran a test, but only had test_mytestfile.R
in your testthat
folder.
Upvotes: 0
Reputation: 52647
Some suggestions / comments:
test_file
without additional setup. This way you can easily run an individual file while developing if you are just focusing on one small part of a larger project (useful if running all your tests is slow)library
multiple times as that function first checks to see if the package is already attachedtest_file
, then test_dir
will work fine without having to do anything additionallibrary(testthat)
in any of your test files since presumably you are running them with test_file
or test_dir
, which would require testthat
to be loadedAlso, you can just look at one of Hadley's recent packages to see how he does it (e.g. dplyr
tests).
Upvotes: 8