Streamlining Rust Development with Snapshot Testing and Insta
What is Snapshot Testing?
Snapshot testing is a method of verifying the correctness of your code by comparing its output to a set of defined, expected values. This approach is particularly useful when managing an ever-changing codebase, as it helps you detect breaks and errors when making updates or changes.
Introducing Insta
Insta is a snapshot testing library for Rust applications that offers a simple and intuitive interface for running and updating tests. With Insta, you can easily debug tests and update failing test outputs with newer ones using the Insta CLI. Insta supports CSV, JSON, TOML, YAML, and RON files via Serde, a data serialization library.
How Insta Works
Insta provides multiple file support using Serde and relies on Cargo’s features to ship all packages seamlessly. The main Insta snapshot assertion library compares two strings, and as long as you pass the SerializationFormat, the assert_snapshot!
macro will compile and work fine. Insta’s runtime consists of the assert_snapshot!
macro, while other macros function as wrappers.
Insta vs. assert_eq
Both Insta and assert_eq
are used for testing, but Insta supports serialization natively, whereas assert_eq
requires manual serialization using Serde. Insta’s comparison process is more lightweight than assert_eq
‘s, making it a more efficient choice.
Getting Started with Insta
To get started with Insta, add the following dependencies to your Cargo.toml
file:
[dependencies]
insta = "1.23.0"
serde = { version = "1.0", features = ["derive"] }
Create a simple to-do list CLI app to track tasks over time. Define each function to add more structure, focusing on the main function. Use Insta to test the add_task
function by adding the following code:
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_add_task() {
let mut tasks = Vec::new();
let task = add_task("New task", &mut tasks);
assert_snapshot!(task);
}
}
Run the tests using the cargo test
command, and all tests should pass successfully.