Macro k9::snapshot [−][src]
macro_rules! snapshot {
($to_snap : expr) => { ... };
($to_snap : expr, $inline_snap : literal) => { ... };
}
Expand description
Serializes the first argument into a string and compares it with the second argument, which is a snapshot string that was automatically generated during previous test runs. Panics if the values are not equal.
If second argument is missing, assertion will always fail by prompting to
re-run the test in update snapshots
mode.
If run in update snapshots
mode, serialization of the first argument will
be made into a string literal and inserted into source code as the second
argument of this macro. (It will actually modify the file in the filesystem)
Typical workflow for this assertion is:
ⓘ
// Step 1:
// - Take a result of some computation and pass it as a single argument to the macro
// - Run the test
// - Test will fail promting to re-run it in update mode
use std::collections::BTreeMap;
k9::snapshot!((1..=3).rev().enumerate().collect::<BTreeMap<_, _>>());
$ K9_UPDATE_SNAPSHOTS=1 cargo test
// Step 3:
// After test run finishes and process exits successfully, the source code of the
// test file will be updated with the serialized value of the first argument.
// All subsequent runs of this test will pass
use std::collections::BTreeMap;
k9::snapshot!(
(1..=3).rev().enumerate().collect::<BTreeMap<_, _>>(),
"
{
0: 3,
1: 2,
2: 1,
}
"
);
ⓘ
// If the logic behind first argument ever changes and affects the serialization
// the test will fail and print the difference between the "old" and the "new" values
use std::collections::BTreeMap;
k9::snapshot!(
/// remove `.rev()`
(1..=3).enumerate().collect::<BTreeMap<_, _>>(),
"
{
0: 3,
1: 2,
2: 1,
}
"
);
The test above will now fail with the following message:
Difference:
{
- 0: 3,
+ 0: 1,
1: 2,
- 2: 1,
+ 2: 3,
}