How to run a specific doctest?

Is there a way to run a specific doctest using cargo test?

I have this code in lib.rs:

/// Some documentation.
///
/// ```
/// let a = 5;
/// ```
pub fn fun() {}

/// Some documentation.
///
/// ```
/// let a = 5;
/// ```
pub fn fun2() {}

Is there a way to "name" the individual doctests so that they can be used with cargo test -- -exact?
cargo test --doc fun -- exact doesn't run the first test.
cargo test --doc fun runs both, but I want to select a specific doctest to run.

cargo test -- --list lists their names like this:

src/lib.rs - fun (line 3): test
src/lib.rs - fun2 (line 10): test

but using these names doesn't work as I would expect.

Try

cargo test --doc 'fun\ (line\ 3)'
3 Likes

Dammit, bash tripped me up :slight_smile: I was trying cargo test --doc "fun (line 3)", but that didn't work. I thought that it's enough to wrap the argument in quotes to handle spaces properly.

Thank you very much!

Actually, I don't think that's the shell's fault. The input to cargo test is a regex, so on this basis, I can imagine space-separated arguments are also handled specially by it unless escaped, which isn't very intuitive. (I came to my solution via trial and error.)

Right, I was quite sure that quoting the spaces should leave them as-is.

This behaviour is quite unintuitive, maybe it could be changed, or at least it could warn about space in the regex. Although running specific doctests is probably a very niche use-case. I only need it for adding the ability to automatically create test run configurations from doctests in the IntelliJ Rust plugin.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.