Redactions

Cargo Feature: redactions

For all snapshots created based on serde::Serialize output insta supports redactions. This permits replacing values with hardcoded other values to make snapshots stable when otherwise random or otherwise changing values are involved. Redactions are an optional feature and can be enabled with the redactions feature.

Redactions can be defined as the third argument to those assertion macros by using the following syntax:

insta::assert_yaml_snapshot!(..., {
    "selector" => replacement_value
});

They can also be configured via settings.

Selectors

The following selectors exist:

Static Redactions

This is an example of simple static assertions:

#[derive(Serialize)]
pub struct User {
    id: Uuid,
    username: String,
    extra: HashMap<String, String>,
}

insta::assert_yaml_snapshot!(&User {
    id: Uuid::new_v4(),
    username: "john_doe".to_string(),
    extra: {
        let mut map = HashMap::new();
        map.insert("ssn".to_string(), "123-123-123".to_string());
        map
    },
}, {
    ".id" => "[uuid]",
    ".extra.ssn" => "[ssn]"
});

Dynamic Redactions

It's also possible to execute a callback that can produce a new value instead of hardcoding a replacement value by using the dynamic_redaction function. This function can also be used to assert that a value follows a specific format before redaction:

insta::assert_yaml_snapshot!(&User {
    id: Uuid::new_v4(),
    username: "john_doe".to_string(),
}, {
    ".id" => insta::dynamic_redaction(|value, _path| {
        // assert that the value looks like a uuid here
        assert_eq!(value
            .as_str()
            .unwrap()
            .chars()
            .filter(|&c| c == '-')
            .count(),
            4
        );
        "[uuid]"
    }),
});

The two arguments to the callback are of type Content and ContentPath. You can find more information in the API documentation about how they work.

Found an issue? You can edit this page on GitHub.