2013-11-15 24 views
3

我在本地环境中调用test_file时遇到问题。R:在本地环境中testthat 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)一些代码,并检查它是有效的(METS一些规定的要求)。我使用的是'local()',因此在shinyAce块中定义的任何分配的变量都不会保留在环境中。

回答

2

下面是test_file来源:

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

重点线是这样的:

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

文件将在一个新的环境中全球环境下执行,而你的newvar只可在您创作的本地环境中使用。

你的最终目标究竟是什么?我们可以尝试帮助。或者你只是好奇?

+0

谢谢。我会更新我的Q,我正在尝试做什么。 – hardingnj

+0

因此'newvar'在测试运行中发生变化?在'simple_test.R'中,你可以创建一个函数,它接受'newvar'参数,然后把所有的测试逻辑放在那里。如果你真的想,你也可以定义自己的'test_file'版本来评估其他环境中的源文件。这些中的一个会起作用吗? – Peyton

+0

我认为编写我自己的test_file版本是最好的解决方案。谢谢你的帮助。 – hardingnj