Table Driven Tests in Rust With Plain Loops and Rstest
Run one test body over many cases. A plain loop works, and rstest gives each case its own name in the output. See both, the failure output and how to keep cases readable.

A function with eight edge cases does not need eight functions that differ in two literals. A table puts the inputs and the expected outputs in one place, and the test body reads once. The question is how failures are reported, which is where the plain loop and rstest differ. This post shows both with the same function. It belongs to the testing in Rust guide.
Rust 1.90, rstest 0.23.
The function under test
pub fn classify(n: i32) -> &'static str {
match n {
i32::MIN..=-1 => "negative",
0 => "zero",
1..=9 => "small",
_ => "large",
}
}A plain loop
#[test]
fn classifies() {
let cases = [
(-5, "negative"),
(0, "zero"),
(7, "small"),
(10, "large"),
];
for (input, expected) in cases {
assert_eq!(classify(input), expected, "input was {input}");
}
}No dependency, easy to read. The weakness: the first failing row stops the test, so you do not see the rest, and the output shows one test. The message input was 10 is what tells you which row failed, so always include it.
rstest
[dev-dependencies]
rstest = "0.23"use rstest::rstest;
#[rstest]
#[case::negative(-5, "negative")]
#[case::zero(0, "zero")]
#[case::small(7, "small")]
#[case::boundary(10, "large")]
fn classifies(#[case] input: i32, #[case] expected: &str) {
assert_eq!(classify(input), expected);
}cargo test lists each case as a separate test:
test classifies::case_1_negative ... ok
test classifies::case_2_zero ... ok
test classifies::case_3_small ... ok
test classifies::case_4_boundary ... okIf boundary fails, the other three still run, and cargo test classifies::case_4 reruns just that one. Case names document intent in the output.
Combinations
#[rstest]
fn works_for_all_pairs(
#[values(1, 2, 3)] a: i32,
#[values("x", "y")] b: &str,
) {
assert!(!b.is_empty() && a > 0);
}#[values] generates the cartesian product, six tests here. Keep the product small, as it grows quickly.
Fixtures
use rstest::fixture;
#[fixture]
fn user() -> User {
User::new("ana")
}
#[rstest]
fn greets(user: User) {
assert_eq!(user.greeting(), "hello ana");
}A fixture is a function whose return value is injected by parameter name. It replaces a setUp method and runs fresh for each test.
Choosing
| Situation | Choice |
|---|---|
| 3 to 6 simple rows, no dependencies wanted | loop |
| Many rows, individual reruns | rstest |
| Cases loaded from files | rstest with #[files] |
| Generated inputs, no fixed rows | proptest |
Limits
Tables with many columns become hard to read; use a struct per case. Do not generate hundreds of cases by hand, because a property test finds more with less text. The crate is documented at docs.rs/rstest, and the broader context is in unit tests.


