Filip
Posted on December 9, 2019
Rust has an interesting feature in its documentation system: if you're writing a library, it will actually compile and run the examples you give in your rustdoc comments as tests. This took me by surprise because I typically don't expect the documentation examples to immediately work, but I see why this is being done - and it's all to do with the fairly obvious: people will copy and paste examples from docs into their code.
So, doctests try to ensure that the examples you give in your doc comments will actually work. Cool, how do we make use of that?
Denial: Not a river in Egypt
You can ignore doctests. Sometimes you may just want to let an example be an example and not be considered a test.
Acceptance: Let it go
You can also just let doctest run your code examples. What you need to keep in mind is that you will need to use
all your types inside the example, like so:
Enlightenment: Writing examples as tests
Tests in Rust are fairly simple - any function that either returns ()
or panics can be a test, and your doctests can be used as regular tests, with asserts and everything:
Galaxy brain: hiding the tests in your docs
But what if you don't actually want to put all the test code and boilerplate in the documentation example itself? Well, rust has you covered too:
And note how this will look in the generated HTML docs:
(Also see the little warning label on the first example? That's because we marked the first example as an ignored test, and the docs will make a note of that - so that's an incentive to keep your doctests passing.)
Even more
Those are just the basics of doctests in Rust, and if you write libraries in this language, you should definitely check out the documentation tests manual for more - and I bet those examples are also tested 🤯
Posted on December 9, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 6, 2024