Writing doctests in DDD is done by building a story about how a piece of code works and should be used. These principles are described in plain English and then a few code usage examples are distributed throughout the text. A good practice is to start to write text on how the code works, and then add some code examples.
To see an example of doctests in practice, let's look at the atomisator package (refer to https://bitbucket.org/tarek/atomisator). The documentation text for its atomisator.parser subpackage (under packages/atomisator.parser/atomisator/parser/docs/README.txt) is as follows:
================= atomisator.parser ================= The parser knows how to return a feed content, with the `parse` function, available as a top-level function:: >>> from atomisator.parser import Parser This function takes the feed url and returns an iterator over its content. A second parameter can specify a maximum number of entries to return. If not given, it is fixed to 10:: >>> import os >>> res = Parser()(os.path.join(test_dir, 'sample.xml')) >>> res <itertools.imap ...> Each item is a dictionary that contain the entry:: >>> entry = res.next() >>> entry['title'] u'CSSEdit 2.0 Released' The keys available are: >>> keys = sorted(entry.keys()) >>> list(keys) ['id', 'link', 'links', 'summary', 'summary_detail', 'tags', 'title', 'title_detail'] Dates are changed into datetime:: >>> type(entry['date']) >>>
Later, the doctest will evolve to take into account new elements or the required changes. Such doctests are also good documentation for developers who want to use the package, and should be evolved with this particular usage in mind.
A common pitfall in writing tests in a document is that they can quickly transform it into an unreadable piece of text. If this happens, it should not be considered as part of the documentation anymore.
That said, some developers that are working exclusively through doctests often group their doctests into two categories: the ones that are readable and usable so that they can be a part of the package documentation, and the ones that are unreadable and are just used to build and test the software.
Many developers think that doctests should be dropped for the latter in favor of regular unit tests. Others even use dedicated doctests for bug fixes. So, the balance between doctests and regular tests is a matter of taste and is up to the team, as long as the published part of the doctests is readable. With modern testing frameworks, like nose or py.test, it's very easy to maintain both collection do doctests and classical function or class-based unit tests at the same time.