R's testthat
package has a number of functions for running tests: https://testthat.r-lib.org/reference/index.html#run-tests. However, the most coarse level you can filter tests seems to be at a file level, since there is a test_file()
function that doesn't have any filtering arguments, and test_dir()
has a filter argument but it is only used to filter by filename.
However I frequently want to only run a single test, because it's new, or because I know it's relevant to a change I just made.
Is there a way, in the R console or in RStudio to run a single testthat
test? If not, is there some other recommended solution to this problem such as putting each test in it's own file (this seems pretty painful though)?
As of testthat
version 3.2.0 CRAN release: 2023-10-06:
test_file() gains a desc argument which allows you to run a single test from a file.
For example, if you have a test file (test-mytest.R
) containing tests for two functions (consider these simple functions converting temperature):
test_that(desc = "Fahrenheit to Celsius", code = {
temp_C <- F_to_C(50)
expect_equal(object = temp_C, expected = 10)
expect_type(object = temp_C, type = "double")
})
test_that(desc = "Celsius to Fahrenheit", code = {
temp_F <- C_to_F(100)
expect_equal(object = temp_F, expected = 212)
expect_type(object = temp_F, type = "double")
})
If you want to run all tests in the file:
R> test_file("tests/testthat/test-mytest.R")
[ FAIL 0 | WARN 0 | SKIP 0 | PASS 4 ]
If you want a single test, use the optional desc
argument to indicate the test name:
R> test_file("tests/testthat/test-mytest.R", desc = "Fahrenheit to Celsius")
[ FAIL 0 | WARN 0 | SKIP 0 | PASS 2 ]