tests/testthat/test-demos.R

test_that("all indexed visual demos run without errors", {
  demo_dir <- system.file("demo", package = "MRS")
  expect_true(nzchar(demo_dir))

  demo_names <- c("mrs_1d", "mrs_2d", "andova_replicates")
  demo_files <- file.path(demo_dir, paste0(demo_names, ".R"))
  expect_true(all(file.exists(demo_files)))

  run_demo <- function(path) {
    output <- tempfile(fileext = ".pdf")
    page_count <- 0L
    previous_hook <- getHook("before.plot.new")
    page_hook <- function(...) {
      if (graphics::par("page")) {
        page_count <<- page_count + 1L
      }
    }
    setHook("before.plot.new", page_hook, action = "append")
    grDevices::pdf(output, width = 9, height = 7, onefile = TRUE)
    on.exit({
      setHook("before.plot.new", previous_hook, action = "replace")
      grDevices::dev.off()
      unlink(output)
    })
    console_output <- utils::capture.output(
      sys.source(path, envir = new.env(parent = globalenv()))
    )
    list(output = console_output, pages = page_count)
  }

  demo_results <- lapply(demo_files, function(demo_file) {
    result <- NULL
    expect_no_error(result <- run_demo(demo_file))
    result
  })

  andova_output <- paste(demo_results[[3L]]$output, collapse = "\n")
  expect_equal(demo_results[[3L]]$pages, 13L)
  expect_match(andova_output, "Small\\s+4")
  expect_match(andova_output, "Medium\\s+10")
  expect_match(andova_output, "Large\\s+20")
  expect_match(andova_output, "pooled MRS is overconfident")
})

Try the MRS package in your browser

Any scripts or data that you put into this service are public.

MRS documentation built on July 22, 2026, 5:10 p.m.