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

Solution 1:

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"))