@@ -382,22 +382,22 @@ indented code blocks.
382
382
383
383
### Include items only when collecting doctests
384
384
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
386
386
sometimes be useful to extend your doctests with samples that wouldn't otherwise need to be in
387
387
documentation. To this end, Rustdoc allows you to have certain items only appear when it's
388
388
collecting doctests, so you can utilize doctest functionality without forcing the test to appear in
389
389
docs, or to find an arbitrary private item to include it on.
390
390
391
391
When 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.
394
394
395
395
In this example, we're adding doctests that we know won't compile, to verify that our struct can
396
396
only take in valid data:
397
397
398
398
``` rust
399
399
/// We have a struct here. Remember it doesn't accept negative numbers!
400
- pub struct MyStruct (usize );
400
+ pub struct MyStruct (pub usize );
401
401
402
402
/// ```compile_fail
403
403
/// let x = my_crate::MyStruct(-5);
@@ -406,7 +406,22 @@ pub struct MyStruct(usize);
406
406
pub struct MyStructOnlyTakesUsize ;
407
407
```
408
408
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.
411
413
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