Hugh
Hugh

Reputation: 16099

devtools::test object not found

I have a series of unit tests that test against a large object (y in the MWE below). I have constructed y in testthat.R, and tests pass if I run R CMD check, but not if I run devtools::test().

How can I ensure devtools::test() runs the test in the correct environment? Or what is the canonical way to make an object available to all tests?

https://github.com/HughParsonage/testGlobalEnv

./tests/testthat.R

library(testthat)
library(testGlobalEnv)

y <- 1:5

test_check("testGlobalEnv")

./R/adder.R

#' Adds numbers
#' @param x A vector of numbers
#' @export

adder <- function(x){
  sum(x)
}

./tests/test_adder.R

test_that("adder", {
  expect_equal(adder(y), 15)
})

R CMD check shows the tests passing; however, running devtools::test():

1
Failed -------------------------------------------------------------------------------------------------------------------
1. Error: adder (@test_adder.R#2) ----------------------------------------------------------------------------------------
object 'y' not found
1: expect_equal(adder(y), 15) at C:\Users\Hugh Parsonage\Documents\Github\testGlobalEnv/tests/testthat/test_adder.R:2
2: compare(object, expected, ...)
3: adder(y)

Upvotes: 4

Views: 1320

Answers (1)

Christoph
Christoph

Reputation: 7063

To the question "what is the canonical way to make an object available to all tests": Just put your shared data, computations, ... in /test/testthat/helper-mytitle.R and it will be available for all tests.

Upvotes: 1

Related Questions