The read_to_test and save_to_test can be replaced by expect_known_output and expect_known_value as follows
# xyz.R
xyz <- function(verbose){
if(verbose)
cat("some output to the console\nin \nmultiple \nlines\n")
1:5
}
# end xyz.R
# testthat/test_xyz.R
test_that("zyx gives correct output", {
expect_known_value(xyz(FALSE), "xyz_results.RDS", update = TRUE)
})
test_that("zyx gives correct output", {
expect_known_output(xyz(TRUE), "xyz_output.txt", update = TRUE)
})
# end testthat/test_xyz.R
# run
source("xyz.R")
setwd("testthat")
# then run the the code in `test_xyz.R`. It creates the following files
readRDS("xyz_results.RDS")
# R [1] 1 2 3 4 5
readLines("xyz_output.txt")
# R [1] "some output to the console" "in " "multiple " "lines"
# and the tests pass when you run
setwd("..")
test_file("testthat/test_xyz.R")
#R √ | OK F W S | Context
#R \ | 2 | 0
#R == Results =====================================================================
#R OK: 2
#R Failed: 0
#R Warnings: 0
#R Skipped: 0
The update argument should be changed to FALSE after the update to ensure that test are not updated if they fail.
The
read_to_test
andsave_to_test
can be replaced byexpect_known_output
andexpect_known_value
as followsThe
update
argument should be changed toFALSE
after the update to ensure that test are not updated if they fail.