@@ -382,22 +382,22 @@ indented code blocks.
382382
383383### Include items only when collecting doctests
384384
385- Rustdoc's [ documentation tests] can do some things that regular unit tests can't, so it can
385+ Rustdoc's documentation tests can do some things that regular unit tests can't, so it can
386386sometimes be useful to extend your doctests with samples that wouldn't otherwise need to be in
387387documentation. To this end, Rustdoc allows you to have certain items only appear when it's
388388collecting doctests, so you can utilize doctest functionality without forcing the test to appear in
389389docs, or to find an arbitrary private item to include it on.
390390
391391When compiling a crate for use in doctests (with ` --test ` option), rustdoc will set ` cfg(doctest) ` .
392- Note that they will still link against only the public items of your crate; if you need to
393- test private items, either make items conditionally public via ` cfg(doctest) ` or write a unit test.
392+ Note that they will still link against only the public items of your crate; if you need to test
393+ private items, you need to write a unit test.
394394
395395In this example, we're adding doctests that we know won't compile, to verify that our struct can
396396only take in valid data:
397397
398398``` rust
399399/// We have a struct here. Remember it doesn't accept negative numbers!
400- pub struct MyStruct (usize );
400+ pub struct MyStruct (pub usize );
401401
402402/// ```compile_fail
403403/// let x = my_crate::MyStruct(-5);
@@ -406,7 +406,22 @@ pub struct MyStruct(usize);
406406pub struct MyStructOnlyTakesUsize ;
407407```
408408
409- Please note that the struct ` MyStructOnlyTakesUsize ` will not appear in documentation or in the
410- public API considering it only exists when running rustdoc with the ` --test ` option.
409+ Note that the struct ` MyStructOnlyTakesUsize ` here isn't actually part of your public crate
410+ API. The use of ` #[cfg(doctest)] ` makes sure that this struct only exists while rustdoc is
411+ collecting doctests. This means that its doctest is executed when ` --test ` is passed to rustdoc,
412+ but is hidden from the public documentation.
411413
412- [ documentation tests ] : documentation-tests.html
414+ Another possible use of ` cfg(doctest) ` is to test doctests that are included in your README file
415+ without including it in your main documentation. For example, you could write this into your
416+ ` lib.rs ` to test your README as part of your doctests:
417+
418+ ``` rust,no_run (includes-extra-file)
419+ #![feature(extern_doc)]
420+
421+ #[doc(include="../README.md")]
422+ #[cfg(doctest)]
423+ pub struct ReadmeDoctests;
424+ ```
425+
426+ This will include your README as documentation on the hidden struct ` ReadmeDoctests ` , which will
427+ then be tested alongside the rest of your doctests.
0 commit comments