Matching elements on complex web pages with Webrat 2
In the first part of this article it was shown how to use CSS selectors for matching elements on complex web pages. But selectors are not the only way of matching HTML elements, Webrat also supports matching via XPath.
XPath matchers can be combined with CSS-selector matchers. This is really useful if not, for example, the content of an element should be matched but the element itself like in the following example. Here a form is used to display data as default value in its input elements. This can be the case in web applications in which data should be edited easily without additional clicks.
<div id="content">
<form>
Label 1: <input id="entry_1" name="entry[1]" value="Entry 1"/>
Label 2: <input id="entry_2" name="entry[2]" value="Entry 2"/>
<input type="submit">
</form>
</div>
Matching the default values of input elements with Webrat can look like the following lines of code. It is a nested combination of CSS-selector and XPath matching in order to have a readable error message if the actual output differs from the expected.
response.body.should have_selector("#content") do |content|
content.should have_tag("form") do |form|
form.should have_selector("#entry_1") do |input|
input.should have_xpath("@value") do |value|
value.should contain("Entry 1")
end
end
end
end
XPath matchers are currently not support by Webrat’s within() method and therefore cannot be used to limit the area on a web page where an action should take place, e.g. clicking of a link. They can only be used for evaluating the response of an action.
Popularity: 1% [?]
