trybuild is a Rust testing tool for compile-time failure scenarios. It compiles test cases separately, checks that they fail or succeed as expected, and compares compiler diagnostics with checked-in output. section 6.4.6
A typical compile-failure test follows these steps:
- Add trybuild as a development dependency, for example with cargo add --dev trybuild or trybuild = "1.0.85". section 6.4.6 section 10.1.1
- Create a test runner under tests and select failure cases with TestCases::new().compile_fail("tests/fails/*.rs"). section 6.4.6
- Place invalid Rust programs in the selected directory, run the test once, and move the generated diagnostic from wip into the test directory as the expected .stderr file. section 6.4.6
- Keep the expected diagnostic under version control so the test verifies that compilation fails for the intended reason. section 6.4.6
Rejecting an enum passed to a derive macro
A test case can apply #[derive(Builder)] to an enum even when the macro supports only named structs. The expected diagnostic records the proc-macro panic and its message: “not implemented: Only implemented for structs.” section 6.4.6
Listing 6.31 Our compilation test runner in the tests folder
#[test]
fn should_not_compile() {
let t = trybuild::TestCases::new();
t.compile_fail("tests/fails/*.rs"); #1
}
The minimal runner demonstrates how trybuild discovers compile-failure cases through a glob. section 6.4.6
