liveBook · Manning

Trybuild

As explained in Write Powerful Rust Macros

trybuild is a Rust testing tool for compiling test cases and checking their expected compiler errors or successful compilation.

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

How Write Powerful Rust Macros covers it

How deep it goes
Explains dependency setup, test-file organization, diagnostic acceptance, and failure-reason verification without covering trybuild internals.
Examples
Uses a missing-field panic test, an enum rejected by a builder derive macro, and configuration-macro compilation tests.
What it assumes
Assumes familiarity with Rust tests, Cargo dependencies, macros, and compiler errors while demonstrating the test workflow.
What you can do after
Build compile-failure tests with TestCases, expected .stderr files, and invalid Rust programs organized under tests.
How it connects
Connects compile-failure testing with Rust procedural macros, derive macros, unit tests, black-box tests, and compiler diagnostics.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Write Powerful Rust Macros. The section links point to the parts of the book it draws on.