How to Run a Specific Test in Rust with Cargo

You can run a specific test by passing its name as an argument to `cargo test`, using either an exact match or a substring filter.

You can run a specific test by passing its name as an argument to cargo test, using either an exact match or a substring filter. This allows you to quickly isolate and verify individual test cases without executing your entire suite.

The most common approach is to use the test name as a filter string. Cargo will run any test whose name contains that string. For example, if you have a test function named test_addition_works, running cargo test test_addition will execute it.

# Run a specific test by name or substring
cargo test test_addition_works

# Run a test in a specific module (e.g., src/lib.rs module 'math')
cargo test math::test_addition_works

If you need to run a test with a very specific name that might conflict with others, or if you want to ensure only one exact test runs, you can combine the filter with the --exact flag (available in newer Cargo versions) or rely on the uniqueness of your naming convention. For more granular control, such as running a test with specific environment variables or in release mode, you can chain additional flags.

# Run a specific test in release mode
cargo test --release test_addition_works

# Run a specific test with verbose output to see exactly what is executing
cargo test test_addition_works -- --nocapture --verbose

Note that the -- separator is crucial when passing arguments directly to the test binary itself (like --nocapture to print stdout/stderr from within the test). Without the separator, Cargo might interpret those flags as its own options. This method works for both unit tests defined in your source files and integration tests located in the tests/ directory. If you have multiple binaries in your project, you can specify which binary to test using --bin or --lib before the test name.

# Run a specific test in a specific binary target
cargo test --bin my_app test_addition_works

This workflow is standard for debugging failing tests or speeding up the development loop when working on a specific feature.