Skip to Content
Course content

181: Snapshot Testing for R Functions

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Why should I bother with snapshots instead of just using expect_equal()?

I've seen a lot of developers try to test functions that return massive objects—think of a 50-column data frame or a deeply nested list of model diagnostics—by manually typing out the expected output in their test file. It's a nightmare. Not only is it tedious, but your test file becomes three thousand lines of hard-coded data that no one wants to read.

Snapshot testing solves this by saying: "I don't know exactly what the output looks like right now, but I know it's correct today. Save this output to a file, and alert me the next time it changes by even one character." It's essentially a way of treating your output as the specification. If you're building a function that generates a complex report or a summary table, snapshots are the only sane way to maintain those tests.

How do I actually set up a snapshot test in R?

In the modern R ecosystem, the testthat package is where this happens. You'll use the expect_snapshot() function. Let's say we have a function called generate_audit_report() that takes a raw dataset and returns a cleaned-up summary of missing values and data types across dozens of columns.

# The function we're testing
generate_audit_report <- function(df) {
  data.frame(
    column = names(df),
    missing = colSums(is.na(df)),
    type = sapply(df, class),
    stringsAsFactors = FALSE
  )
}

# In your test file (e.g., tests/testthat/test-audit.R)
test_that("audit report matches the gold standard", {
  my_data <- data.frame(x = c(1, NA, 3), y = c("a", "b", "c"), z = c(TRUE, FALSE, NA))
  
  # This will create a .snap file in a snapshots directory the first time it runs
  expect_snapshot(generate_audit_report(my_data))
})

The first time you run this, the test will actually fail. That's normal! testthat is telling you, "I didn't find a snapshot, so I created one for you." Once that file is written to disk, every subsequent run will compare the current output against that file.

What do I do when the test fails because I actually changed the function?

This is where snapshot testing can feel a bit jarring at first. You'll make a deliberate change to your function—maybe you renamed a column in your report—and suddenly your tests are red. You don't want to go hunting through a .snap file in a hidden folder to manually edit text.

Instead, you "approve" the new version. In testthat, you can do this by passing approve = TRUE to the snapshot function temporarily, or by using the snapshot_approve() utility if you're using a more recent version of the framework. I usually just do this:

# Temporarily change to approve the new output
expect_snapshot(generate_audit_report(my_data), approve = TRUE)

Run the test once to overwrite the old snapshot with the new "correct" version, then remove the approve = TRUE argument. It's a fast workflow, but a word of caution: don't get into the habit of blindly approving snapshots. Actually look at the diff in your console to make sure you didn't accidentally break something you didn't intend to.

Can I use snapshots for things that aren't just data frames?

Absolutely. I actually use them more often for complex lists or raw string output. If your function returns a customized JSON string or a formatted Markdown table, expect_snapshot() handles it perfectly because it's essentially comparing text.

If you're doing heavy visualization work, you'll want to look at the vdiffr package. It's basically snapshot testing but for ggplot2 objects. Instead of comparing text, it compares the visual rendering of the plot. I've found it saves me hours of squinting at plots to see if a legend moved two pixels to the left after a dependency update.




📋 Practical Task

Stabilizing the Financial Summary Snapshot

You are maintaining a financial analysis package. There is a function called summarize_portfolio() that returns a detailed list containing a summary data frame and a character vector of warnings. The existing snapshot test is failing because the output format was recently updated to include a "Currency" column.

Your Goal: Update the snapshot to reflect the new output and ensure the test passes.

Starter Code:

library(testthat)

summarize_portfolio <- function(assets) {
  # New version of the function adds the 'Currency' column
  list(
    summary = data.frame(
      Asset = assets,
      Value = c(100, 200, 150),
      Currency = c("USD", "USD", "EUR"),
      stringsAsFactors = FALSE
    ),
    warnings = c("High volatility detected in Asset 3")
  )
}

# The test currently fails because the stored snapshot 
# (which you can imagine is on disk) lacks the 'Currency' column.
test_that("Portfolio summary matches expectations", {
  assets <- c("AAPL", "GOOGL", "SAP")
  expect_snapshot(summarize_portfolio(assets))
})

Instructions: Modify the expect_snapshot() call in the test block to approve the new data structure, then revert the call to its standard state so the test remains a guardrail for future changes.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.