evaluation inside of test_that call

2019-07-11 22:52发布

问题:

I am trying to write some unit tests for my package and having difficulty getting a test of the gls function from nlme to work. MWE:

library(testthat)
library(nlme)
data(Ovary, package = "nlme")
test_that("getData works.", {
  re_order <- sample(nrow(Ovary))
  egg_scramble <- Ovary[re_order,]
  gls_scramble <- gls(follicles ~ sin(2*pi*Time) + cos(2*pi*Time), 
                     data = egg_scramble)
  dat <- getData(gls_scramble)
  expect_identical(egg_scramble, dat)
})

For some reason, the getData call cannot find the data within the test environment. Here is the the traceback:

Error: Test failed: 'getData works.'
Not expected: object 'egg_scramble' not found
1: withCallingHandlers(eval(code, new_test_environment), error = capture_calls)
2: eval(code, new_test_environment)
3: eval(expr, envir, enclos)
4: getData(gls_scramble) at :6
5: getData.gls(gls_scramble)
6: eval(if ("data" %in% names(object)) object$data else mCall$data)
7: eval(expr, envir, enclos).

And yet, evaluating the same code outside of test_that does not lead to an error:

re_order <- sample(nrow(Ovary))
egg_scramble <- Ovary[re_order,]
gls_scramble <- gls(follicles ~ sin(2*pi*Time) + cos(2*pi*Time), 
                    data = egg_scramble)
dat <- getData(gls_scramble)
identical(dat, egg_scramble)
标签: r testthat