3

我在本地环境中调用 test_file 时遇到问题。

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

工作正常。

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

工作正常。

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

错误:找不到对象“newvar”

simple.test.R 的内容很简单:

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

帮助表示赞赏!谢谢。


编辑:

我要做的是从 shinyAce ( https://github.com/trestletech/shinyAce ) 读取一些代码,并检查它是否有效(满足一些定义的要求)。我正在使用“local()”,因此在 shinyAce 块中定义的任何分配变量都不会保留在环境中。

4

1 回答 1

2

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?

于 2013-11-15T03:26:23.993 回答