2

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)
Pusto
  • 55
  • 4
  • 1
    Potentially related questions, none of which have any answers: [here](http://stackoverflow.com/questions/34345945/test-that-with-match-fun-throws-unexpected-error-when-used-two-levels-deep), [here](http://stackoverflow.com/questions/32728107/unit-test-works-as-standalone-but-fails-in-test-that-call), [here](http://stackoverflow.com/questions/31501580/bootstrap-code-works-in-examples-but-not-with-testthat), and [here](http://stackoverflow.com/questions/30563122/object-no-found-error-in-testthat-tests). – Pusto Mar 28 '16 at 02:49
  • It seems that `gls()` looks for `egg_scramble` in the global environment. If I make sure that `egg_scramble` is defined in the global environment, I don't get this error message (but then the test fails, of course). That said, I know no solution to this apart from taking all lines except the `expect_identical()` out of the `test_that`. Might this be a bug in testthat? – Stibu Mar 28 '16 at 09:53
  • @Stibu I agree with your diagnosis. It turns out that taking all the lines out of test_that except for the expectation does work for the MWE. However, when running the test via `devtools::test()`, I get essentially the same error. I think it is because testthat:::test_file runs each test in a new environment. As far as it being a bug in testthat, I suspect it's more likely an issue with how `getData` uses evaluation. – Pusto Mar 28 '16 at 14:43

0 Answers0