Better error messages when testing html views

less than 1 minute read

When testing html views, either from RSpec or from Cucumber, XPath can be really helpful to quickly find expected elements.

Unfortunately, a bit like regular expressions, when you start to use xpath to solve a problem, you often end up with 2 problems … Part of the reason is that xpaths tend to be cryptic. In the case of testing, error messages coming from unmatched xpath are even more crytic !

That’s why I had the idea for xpath-specs : a small gem that allows to associate a description with an xpath, to nest xpaths together, all this to simplify tests and assertion failure reporting.

For example, with an assertion like this :

expect(html).to contain_a(dish_with_name("Grilled Lobster")

Here is the kind of failure message one can get :

expected the page to contain a dish that is named Grilled Lobster (//table[@id='dish-panel']//tr[td[contains(.,'#{name}')]])
       it found a dish (//table[@id='dish-panel']//tr) :
       but not a dish that is named Grilled Lobster (//table[@id='dish-panel']//tr[td[contains(.,'#{name}')]])

And here is the required setup :

# spec/support/knows_page_parts.rb

module KnowsPageParts
  def dish"a dish", "//table[@id='dish-panel']//tr")

  def dish_with_name(name)
    dish.that("is named #{name}", "[td[contains(.,'#{name}')]]")

Have a look at the readme for more details.

I usually write about 15 minutes worth of reading per month. I won't transfer your email. No Spam, unsubscribe whenever you want.

As a gift for subscribing, you'll receive an illustrated mini-ebook "How to start a team coding dojo"!