rtestthatcovr

r testthat and covr use in a non-package library


I'd like to be able to use testthat and covr in a project that is not an r package. In fact does not use any third party services. Just a collection of plain-old-r source files

I am struggling to find out if this is possible, and if so, the instructions on how to set this is up.

What I have found assumes you are writing an r package. I like to avoid this overhead.

Prior Art:

  1. https://www.rstudio.com/resources/webinars/covr-bringing-test-coverage-to-r/
  2. https://walczak.org/2017/06/how-to-add-code-coverage-codecov-to-your-r-package/

Solution

  • That should be possible without problems.

    First: I have one file with code that should be tested named code.R:

    f1 <- function(n, ...) {
        rnorm(n = n, ...)
    }
    

    Second: Then I have a file with tests named tests.R:

    source("code.R")
    
    test_that("Random tests", {
        tmp1 <- f1(10)
        expect_type(tmp1, "double")
        expect_equal(length(tmp1), 10)
    })
    

    Third: And then you can run tests as well as coverage like this:

    library(testthat)
    library(covr)
    
    test_file("tests.R")
    
    res <- file_coverage("code.R", "tests.R")
    res
    report(res)
    

    Multiple files should be no problem.