Is R CMD check (devtools:check()) with keep.source = TRUE possible?
I'm writing unit tests using testthat
to check some operations and these operations needs objects with srcref
attribute. srcref
attribute is added if during the package installation / building option keep.source
was set to TRUE
.
I see all my tests fail when using devtools::check()
if those tests expect srcref
attribute for object. This not happens when tests are performed interactively, i.e. using devtools:test()
. What could I do to keep these tests, run it and make them pass using devtools::check()
? I have tried devtools::check(args = "--with-keep.source")
but this argument is not recognized.
I'm using rlang::pkg_env("my-package")
to get objects with srcref
attribute, so tests look like this:
testthat("my example works", {
expect_true(!is.null(get_srcref_for_some_object(names(rlang::pkg_env("my-package")))))
})
Solution 1:
The option --with-keep.source
is for R CMD INSTALL
, not R CMD check
. To make sure that check
preserves sources when it installs your package, you need to run
R CMD check /path/to/tarball --install-args=--with-keep.source
in a shell or
devtools::check("path/to/package", args = "--install-args=--with-keep.source")
in R.
Minimal reproducible example
pkgname <- "foo"
usethis::create_package(pkgname, rstudio = FALSE, open = FALSE)
setwd(pkgname)
usethis::use_testthat()
text <- "
#' @title A title
#' @description A description.
#' @param a,b Arguments.
#' @examples
#' x <- add(1, 1)
#' @export
add <- function(a, b) a + b
"
cat(text, file = file.path("R", "add.R"))
devtools::document(".")
text <- "
test_that(\"sources kept\", {
expect_false(is.null(attr(add, \"srcref\")))
})
"
cat(text, file = file.path("tests", "testthat", "test-add.R"))
devtools::check(".")
─ checking tests ...
─ Running ‘testthat.R’ (357ms)
E Some test files failed
Running the tests in ‘tests/testthat.R’ failed.
Last 13 lines of output:
> library(foo)
>
> test_check("foo")
[ FAIL 1 | WARN 0 | SKIP 0 | PASS 0 ]
══ Failed tests ════════════════════════════════════════════════════════════════
── Failure (test-add.R:3:3): sources kept ──────────────────────────────────────
is.null(attr(add, "srcref")) is not FALSE
`actual`: TRUE
`expected`: FALSE
[ FAIL 1 | WARN 0 | SKIP 0 | PASS 0 ]
Error: Test failures
Execution halted
devtools::check(".", args = "--install-args=--with-keep.source")
─ checking tests ...
✓ Running ‘testthat.R’
Clean
setwd("..")
unlink(pkgname, recursive = TRUE)