snapshot_testing/
lib.rs

1/// Assert that `value` matches the snapshot at `snapshot_path`. If there is a
2/// mismatch the function will panic with a helpful diff that shows what
3/// changed.
4///
5/// If the env var `UPDATE_SNAPSHOTS` is set to `1`, `yes` or `true` then
6/// `value` will be written to `snapshot_file` instead of being asserted to
7/// match.
8pub fn assert_eq_or_update(value: impl AsRef<str>, snapshot_path: impl AsRef<std::path::Path>) {
9    let value = value.as_ref();
10    let snapshot_path = snapshot_path.as_ref();
11
12    if update_snapshots() {
13        std::fs::write(snapshot_path, value)
14            .unwrap_or_else(|e| panic!("Error writing {snapshot_path:?}: {e}"));
15    } else {
16        let snapshot = std::fs::read_to_string(snapshot_path)
17            .unwrap_or_else(|e| panic!("Error reading {snapshot_path:?}: {e}"));
18
19        similar_asserts::assert_eq!(value, snapshot);
20    }
21}
22
23fn update_snapshots() -> bool {
24    std::env::var("UPDATE_SNAPSHOTS")
25        .map(|s| s.to_lowercase())
26        .is_ok_and(|s| s == "1" || s == "yes" || s == "true")
27}