Sub topic 11
Dev-dependencies for tests and examples
This chapter assumes you can read a Cargo.toml, add a normal dependency, and write a basic #[test] function. It also assumes you know the layout of a package: src/, tests/, and the idea that a package can contain a library crate and binaries. Here you learn how to declare crates that only your tests, examples, and benchmarks need, and what Cargo does with them.
What a dev-dependency is
A dev-dependency is a crate that your package needs while you develop it, but not to build or use it. Typical cases are assertion helpers, temporary-file utilities, mocking libraries, and benchmark harnesses.
You declare them in their own table:
[package]
name = "my_geometry"
version = "0.1.0"
edition = "2021"
[dependencies]
serde = { version = "1", features = ["derive"], optional = true }
[dev-dependencies]
pretty_assertions = "1"
tempfile = "3"
[features]
default = []
serde = ["dep:serde"]The syntax inside [dev-dependencies] is the same as in [dependencies]. You can use version requirements, path, git, features, default-features = false, and package renames. The one exception is optional = true, which is not allowed on dev-dependencies.
You can also add one from the command line:
cargo add --dev pretty_assertionsWhere dev-dependencies are available
Cargo compiles a dev-dependency only when it builds a target that can use it. These targets are:
- unit tests (code under
#[cfg(test)]insrc/) - integration tests in
tests/ - examples in
examples/ - benchmarks in
benches/ - documentation tests
Plain cargo build and cargo run skip them. They are not downloaded into the compile graph for your library or binary, so they do not slow down a normal build.
The key point is that normal dependencies are visible everywhere, while dev-dependencies are visible only to the development targets.
Using a dev-dependency in a unit test
Dev-dependencies work inside a #[cfg(test)] module in src/. This example uses pretty_assertions, whose assert_eq! prints a colored diff when two values differ.
#[derive(Debug, PartialEq)]
pub struct Rect {
pub width: u32,
pub height: u32,
}
impl Rect {
pub fn square(side: u32) -> Rect {
Rect { width: side, height: side }
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn square_has_equal_sides() {
assert_eq!(Rect::square(4), Rect { width: 4, height: 4 });
}
}The use pretty_assertions::assert_eq; line shadows the standard assert_eq! macro inside this module only. Code outside the tests module still uses the standard one.
The #[cfg(test)] attribute matters here. If you wrote the same use at the top level of src/lib.rs, a normal cargo build would fail, because the crate is not available outside test builds.
Using a dev-dependency in an integration test
Files in tests/ are compiled as separate crates, and they see both normal dependencies and dev-dependencies. This test uses tempfile to create a directory that is deleted when the test ends:
// tests/files.rs
use std::fs;
#[test]
fn writes_and_reads_a_file() -> Result<(), Box<dyn std::error::Error>> {
let dir = tempfile::tempdir()?;
let path = dir.path().join("note.txt");
fs::write(&path, "hello")?;
assert_eq!(fs::read_to_string(&path)?, "hello");
Ok(())
}Every test file in tests/ is its own crate, but all of them share the same [dev-dependencies] list.
Examples
An example is a small program in the examples/ directory. It uses your library the way an outside user would, so it is useful as documentation that the compiler checks. Cargo finds examples/*.rs automatically.
// examples/basic.rs
use my_geometry::Rect;
use pretty_assertions::assert_eq;
fn main() {
let r = Rect::square(3);
assert_eq!(r.width, r.height);
println!("{:?}", r);
}Run it with the --example flag and the file name without .rs:
cargo run --example basiccargo test also builds every example, though it does not run them. A broken example therefore fails your test run, which keeps examples from going stale. If a dev-dependency is needed only by examples, it still belongs in [dev-dependencies], because Cargo has no separate table for examples.
What dev-dependencies do not do
Three behaviors catch people out.
- They are not passed on to your users. If another package depends on
my_geometry, Cargo does not buildpretty_assertionsortempfilefor it. Dev-dependencies of your dependencies are also ignored when you build your own package. - They cannot be used in non-test source. Importing a dev-dependency in a library or binary module gives an
unresolved importoruse of undeclared crateerror oncargo build. The fix is either to wrap the code in#[cfg(test)]or to move the crate to[dependencies]if the shipped code really needs it. - They count for the lock file.
Cargo.lockrecords the versions of dev-dependencies too. Your tests are therefore reproducible, even though your users never build these crates.
A related point is that features of a dev-dependency can affect a normal dependency only if both name the same crate. With resolver = "2", which is the default for edition 2021 packages, Cargo does not turn on a shared crate's features for a normal build just because a dev-dependency requested them. With the older resolver, those features could leak into a normal build. Check that your manifest uses the newer resolver, especially in a workspace, where you set it in the root:
[workspace]
resolver = "2"
members = ["core", "cli"]Choosing between the three dependency tables
| Table | Used by | Built for `cargo build` | Passed to users |
|---|---|---|---|
| `[dependencies]` | Library and binary code, and also tests | Yes | Yes |
| `[dev-dependencies]` | Tests, examples, benchmarks, doc tests | No | No |
| `[build-dependencies]` | The `build.rs` script only | Yes, for the build script | No |
When you are unsure where a crate belongs, ask which code imports it. If code in src/ outside #[cfg(test)] imports it, it is a normal dependency. If only tests or examples import it, it is a dev-dependency.
Variations worth knowing
Dev-dependencies can be limited to a platform, using the same target syntax as other dependency tables:
[target.'cfg(unix)'.dev-dependencies]
nix = "0.29"A path dev-dependency may also carry a version, which is required if you publish the package:
[dev-dependencies]
test_helpers = { path = "../test_helpers", version = "0.1.0" }If you leave the version out, cargo publish strips the dev-dependency before packaging, so the published crate still builds. Be aware that this means the published tests cannot compile, so users who run cargo test on the packaged source see failures.
A package may also list itself as a dev-dependency with extra features turned on. This lets its tests exercise a feature that is off by default:
[dev-dependencies]
my_geometry = { path = ".", features = ["serde"] }Many projects use this to test optional features without passing --features every time. It works, but it makes the dependency graph harder to read, so a plain cargo test --features serde is often clearer.
Common errors
- Test crate in
[dependencies]. The code compiles, but every user of your library now downloads and builds the test crate. Move it. useof a dev-dependency at module level. The test build passes andcargo buildfails. Runcargo buildas well ascargo testbefore you push.- Forgetting that examples and doc tests count. A dev-dependency removed because "the tests don't use it" can still be needed by
examples/or a doc comment. - Shared test helpers. If several crates in a workspace need the same helper code, put it in its own member crate and add it as a path dev-dependency, as shown above, instead of copying files.
Exercise
Your library's src/lib.rs has use tempfile::tempdir; at the top, and tempfile is listed only under [dev-dependencies]. cargo test passes but cargo build fails. Explain why, and give two valid ways to fix it.
Show answer
cargo test builds dev-dependencies, so the import resolves. cargo build does not build them, so the crate is undeclared and the import fails. Fix 1: if only tests use tempdir, move the use line (and its uses) into a #[cfg(test)] mod tests block. Fix 2: if the shipped code really needs tempfile, move it from [dev-dependencies] to [dependencies].
Exercise
Which of these gets built by cargo build with no other flags: a crate in [dev-dependencies], a crate in [dependencies], or both? And does a user who depends on your package build your dev-dependencies?
Show answer
Only the crate in [dependencies] is built. A user who depends on your package does not build your dev-dependencies.