Drupal 6: Using XPath in your SimpleTest tests

14th Jul 2010 // By Otto // Drupal Planet

Sometimes we need to do more than test whether a particular piece of text is on the page. Using XPath, we can examine the DOM (the structure of elements making up the page) and get ourselves a nice extra bit of information that we can use to write more robust tests.

In our example, we have a table of results, and we want to test the number of rows that are in the table. We might be using an API function or a node edit form in order to add some information, and as that information is added, we would expect to see more and more rows in the table.

A table in the Drupal admin interface

This is not easy to test using $this->assertText because we need to know how many times a particular piece of text is on the page, not just that is it there. This is also not easy to test using $this->assertRaw.

This table is generated by theme('table') and if we were to start testing for things like specific HTML strings, we would run the risk of the test failing if the implementation of theme('table') changed (someone had written a custom theme with table output that adds special classes to the tr tags, for example.

Ideally, we want to test that there are three (for example) rows in the table. Rather than use $this->assertFieldByXPath, which is only useful for form fields, we can use SimpleTest's $this->xpath method to get the data we need, then use a more conventional assertion.

  1. $this->drupalGet('admin/mymodule/mytable');
  2. $rows = $this->xpath(
  3.   "//table[@id='mymodule-shares-table']/tbody/tr"
  4. );
  5. $this->assertEqual(
  6.   3,
  7.   count($rows),
  8.   t('Three rows in the share table')
  9. );

We know that the table has a specific id attribute, so we have used that to find it in the DOM, then selected its immediate children to find the rows we want.

Of course, this does assume that the tbody tag is a child of the table tag, and that the tr tags are children of the tbody tag. This is a safe assumption, because the page would not be valid XHTML if this were not the case. There's always the possibility that theme('table') doesn't actually output a table tag, but that's a pretty long stretch. ;)

The $this->xpath method returns a chunk of the DOM as an array, and we can simply count the number of elements in the array to find how many tr tags there are, and hence how many rows are in our table. We can then use the regular $this->assertEqual method to perform a SimpleTest test.

Do let us know if you'd have done it differently, or if you have any tips for using XPath to create better SimpleTest tests!

0

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.

New job vacancies button