Snapshot test with insta

Snapshot test with insta

(Jin Qing’s Column, Dec., 2023)

Insta crate is for unit test.
It asserts the value comparing to the snapshot value.
Usually the value is complex and the comparison is by the serialized string form.

Reference: https://insta.rs/docs/quickstart/

First add insta into the project:

cargo add insta --dev --features yaml

yaml is the suggested form of the snapshot.

Write a test case using assert_yaml_snapshot!():

fn split_words(s: &str) -> Vec<&str> {
    s.split_whitespace().collect()
}

#[test]
fn test_split_words() {
    let words = split_words("hello from the other side");
    insta::assert_yaml_snapshot!(words);
}

The first run of cargo test will fail and generate src/snapshots/test_insta__split_words.snap.new:

---
source: src/main.rs
assertion_line: 13
expression: words
---
- hello
- from
- the
- other
- side

Rename *.snap.new file into *.span, then further tests will compare the value with the snapshot file.

Or use cargo insta review to review the spanshot file.

你可能感兴趣的:(Rust,开发语言,rust)