Search code examples
rdevtoolstestthatrenv

testthat and roxygen for analytical projects that are not packages


I try to find out how I can use some devtools features like testthat, roxygen etc., when I work with an R project that is not a package. In the "R Packages (2e)" book, there are good examples how I can use all this features. But when I try to use this in a project that is not a package, I will receive error messages, e.g. the following:

test() Error in package_file(): ! Could not find package root. ℹ Is . inside a package? Run rlang::last_trace() to see where the error occurred.

I work within a project that I did not setup as a package. The usethis package documentation mentions this option explicitly, but I could not find any examples how this works in practice. All documentations I could find refer to package development.


Solution

  • Probably it would make sense if you just set up a package - it makes live easier since both roxygen2 and testthat are mostly designed to work with packages. If you are using RStudio you also can just comfortably trigger the Built and Check- buttons to create roxygen documentation or check your package.

    As Karolis mentioned in the comments, an R package is not much more than having a DESCRIPTION file and an R folder, where your R files are stored. (and a folder tests, when you want to have tests)

    But if you do not want to set up a package you can of course also use testthat within a normal project.

    Just write a testthat test and store it in an .R file.

    E.g. take this test (of course replace it with something more useful) and put it in a R file my_test.R assume it is in a folder called tests.

    testthat::expect_identical(1,1)
    

    Afterwards you can call test_file()

    testthat::test_file(path = "tests/my_test.R")
    

    And you get an output like this:

    [ FAIL 0 | WARN 0 | SKIP 0 | PASS 1 ]

    If you have multiple files with tests, you can just call test_dir() to check a whole folder

    So to check all files in the tests folder you would write:

    testthat::test_dir(path = "tests")
    

    Be aware, in your tests files you will have to source your code first, otherwise testthat does not have the functions you defined loaded. Using a package you do not have to do this.

    source("/R/my_code.R")
    test_that("Add", 
    {
       expect_equal(my_add_function(1,1), 2)
    })
    

    So you have to source my_code.R to have your my_add_function function loaded, to test it with testthat. (as mentioned with a package you don't need to source your code contents)