Testthat: create shared variables between unit tests which don't survive the test file

Viewed 152

I have a piece of sequential code and I would like to test every piece of it. The problem is that each piece needs the output of the precedent one as input.

testthat::test_that() calls encapsulate the code and therefore every variable created in it gets destroyed after the test. I thought of using <<- but it puts the variables in the global environment even if I wrap all the tests in a local() call. Also I would like these variables not to survive each test file, so that I'm sure of what I am testing.

Here some test code:

local({
    test_that('test 1', {
        foo <<- 1
        expect_equal(foo, 1)
    })

    test_that('test 1', {
        bar <- foo + 1
        expect_equal(bar, 2)
    })
})

print(exists("foo")) # should not exists but it does
print(exists("bar"))

I'd like to use "foo" in the second test but be sure that it doesn't get in the global env and doesn't leave the test file.

1 Answers

The rule for <<- is that it looks up the environment tree until it finds the variable, and assigns in globalenv() if that search fails. So you just have to make sure the search succeeds and you won't leave leftovers:

local({
    foo <- NULL  # so that the <<- assignment stays local

    test_that('test 1', {
        foo <<- 1
        expect_equal(foo, 1)
    })

    test_that('test 1', {
        bar <- foo + 1
        expect_equal(bar, 2)
    })
})

print(exists("foo")) # should not exist, and doesn't!
print(exists("bar"))
Related