Question

I am having problems with a call to test_file within a local environment.

local({ newvar <- 1; expect_equal(newvar, 1); });

Works fine.

local({ 
  newvar <- 1; 
  test_that('newvar is equal to 1:', { expect_equal(newvar, 1) }); 
});

works fine.

local( { newvar <- 1; test_file('simple.test.R'); });

Error: object 'newvar' not found

Contents of simple.test.R are simply:

context('local env test');
test_that('local env test', { expect_equal(newvar, 1) })

Help appreciated! Thanks.


Edit:

What I'm trying to do is read some code from shinyAce (https://github.com/trestletech/shinyAce), and check it is valid (mets some defined requirements). I was using 'local()' so that any assigned variables defined in the shinyAce block would not remain in the environment.

Was it helpful?

Solution

Here's the source for test_file:

function (path, reporter = "summary") 
{
    reporter <- find_reporter(reporter)
    with_reporter(reporter, {
        sys.source(path, new.env(parent = globalenv()), chdir = TRUE)
        end_context()
    })
}

The key line is this:

sys.source(path, new.env(parent = globalenv()), chdir = TRUE)

The file is executed in a new environment under the global environment, while your newvar is only available in a local environment of your creation.

What exactly is your end goal here? We can try to help. Or were you just curious?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top