Search code examples
rtestingread.tabletestthatwrite.table

How to work with "example files" using testthat in R?


I'm creating an R package using testthat. Many of the functions I am working with require a file as input and/or write a file to output.

Currently, my R package directory structure looks roughly like:

- R_package_name
    -/tests
        -/testthat.R
        -/testthat
            -/test_package.R

As an example, functions in this category would be read.table() and write.table(). The former reads in some file, the latter writes it.

What is the standard for creating "example files" for tests with testthat given the R package structure? I could create very small example files as inputs in the tests

Let's say I'm doing a test for write.table():

test_that("check write.table", {

    df = data.frame( n = c(2, 3, 5), s = c("aa", "bb", "cc"), b = c(TRUE, FALSE, TRUE))
    expect_identical(write.table(df), ???)

})

EDIT: Apparently mock's are possible in R: https://rdrr.io/a/cran/testthat/man/with_mock.html


Solution

  • My understanding was that the standard was to store data in the package as a .RData object in the \data folder of a given package, and that if you wanted to test reading in that data, you had to essentially call that data set, write a file, test reading it in, then cleanup.

    However, looks like there may be a way to store raw data files, check out this link on handling raw data. Here is another useful link on creating an R data package. creating an R data package