R
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Data Structures
-
Section 4: Data Manipulation
-
Section 5: Visualization and Statistics
-
Section 6: Advanced R
-
Section 7: Practical Projects
-
Section 8: Interview Practice
-
Section 9: More Practice Exercises
-
Section 10: Shiny Apps in Depth
-
Section 11: More Data Wrangling
-
Section 12: Tidyverse Deep Dive
-
Section 13: Statistical Modeling Deep Dive
-
Section 14: Machine Learning in R
-
Section 15: R Visualization Deep Dive
-
Section 16: R Package Development Deep Dive
-
Section 17: R for Reproducible Research
-
Section 18: R and Databases
-
Section 19: R Performance Optimization
-
Section 20: Bioinformatics and Specialized R
-
Section 21: More Shiny Practice
-
Section 22: More Practice Exercises
-
Section 23: R Data Structures Deep Dive
-
Section 24: More Interview and Review
-
Section 25: R for Business Analytics
-
Section 26: R Text Mining and NLP
-
Section 27: R Spatial Data Analysis
-
Section 28: R Deep Learning
-
Section 29: Advanced Statistical Techniques
-
Section 30: R Object Systems Deep Dive
-
Section 31: R Environments and Metaprogramming
-
Section 32: R for Finance
-
Section 33: R for Clinical and Health Data
-
Section 34: More Shiny Advanced Practice
-
Section 35: R Data Cleaning Deep Dive
-
Section 36: R Reporting Automation
-
Section 37: More Practical Projects Round 2
-
Section 38: R Ecosystem and Career
-
Section 39: More Visualization Practice
-
Section 40: R for Experimentation
-
Section 41: R for Genomics and Bioinformatics Deep Dive
-
Section 42: R for Marketing Analytics
-
Section 43: R Data Import/Export Deep Dive
-
Section 44: R String Processing Deep Dive
-
Section 45: R for Actuarial and Insurance Analytics
-
Section 46: R Testing and Quality Assurance Deep Dive
-
Section 47: R Version Control and Collaboration
-
Section 48: R Advanced Functional Programming
-
Section 49: R for Supply Chain and Operations
-
Section 50: More Practice Exercises Round 3
-
Section 51: R Dashboards and BI Integration
-
Section 52: R Data Governance and Ethics
-
Section 53: More Modeling Practice
-
Section 54: R Final Capstone Projects
-
Section 55: R for Sports Analytics
-
Section 56: More Interview Practice Round 2
-
Section 57: R Networking and APIs
-
Section 58: R for Environmental Science
-
Section 59: R Notebook and Documentation Practices
-
Section 60: More Data Wrangling Mastery
-
Section 61: R for A/B Testing at Scale
-
Section 62: R Package Ecosystem Deep Dive
181: Snapshot Testing for R Functions
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.
There are no comments for now.