snapshot_testing/
lib.rs

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