Tom
Tom

Reputation: 1105

Capybara Regex with Find

I'm trying to write something generic in the interim for an app that's being developed. The header elements are constantly changing between h2 and h3, and are causing unnecessary failures. I want something a little more specific that expect(page).to have_text ...

What I want to do is write a find command in Capybara that will place a regex for a digit in the code. Like so:

def locate_headers(arg)
  header = find(/h(\d+)/, text: arg)
 end

I'm hoping this would find the H element on screen that matches the text.

I get the following error:

Selenium::WebDriver::Error::InvalidSelectorError: invalid selector: An invalid or illegal selector was specified

I don't have a lot of experience with Regex. Is what I want to do, possible?

Thanks

Upvotes: 0

Views: 926

Answers (2)

Thomas Walpole
Thomas Walpole

Reputation: 49880

CSS selectors don’t support regex matching but they do support OR matching with the CSS comma. This means you can get what you want with

def locate_header(arg)
  header = find('h2, h3', text: arg)
end

which will find either an <h2> or <h3> element containing the given text

Upvotes: 4

Tomasz Giba
Tomasz Giba

Reputation: 541

find takes an CSS selector as argument, not a RegEx one. Hence the "illegal selector".

Having this in mind, there's :header selector that selects headers only. However, I am not sure if it is compatible with Capaybara link

Upvotes: 0

Related Questions