Recently I was writing custom Xml exporting for some of our Rails models. I favor TDD over just shoot-from-the-hip development, so I had to write some tests. For testing the validity of the XML, I chose XPath for its simplicity.
As I added functionality (and thereby added tests) I noticed that my tests were becoming increasingly redundant, and that Test::Unit's syntax was making my test files ugly and more importantly hard to read. As I started DRY-ing up the individual tests and trying to find better ways to share code and make the tests more succinct, I noticed that I was driving very close to creating my own mini-DSL for testing Xml with Xpath.
My Requirements for Xml Exporting
A required element must always exist in the resulting Xml regardless of the model's state
An optional element:
Must exist when the model meets a certain state condition (i.e. the member is not null)
Must not exist when that condition is not met
A DSL That Meets My Testing Needs
As mentioned earlier, this DSL evolved from repeated refactoring my tests in order to make them more clear. Here is an example of an XPath-based Xml test:
[sourcecode lang='ruby']
xpath_tests_for @video_library do
# ensure that the Xml always contains:
#
No Comments »