nrp
nrp

Reputation: 451

Capybara: simple way to find elements without particular text

There are several elements on the page, and I need an array of them, but without an element with particular text. What I do now is

tabs_quantity = page.all(:css, 'div.class1 ul.tabs li.tab.exist', visible: true)
tabs_quantity.each { |x|
  if x.text != 'Main'
    ...blah-blah-blah...

I`ve seen only ":text => 'Text' everywhere but what I need is opposite to equality, so I've searched and tested but have not find if there is something simple like

tabs_quantity = page.all(:css, 'div.class1 ul.tabs li.tab.exist', visible: true, :text !=> //or "not equal", whatever// 'Main')

Thanks.

Upvotes: 1

Views: 950

Answers (2)

tgf
tgf

Reputation: 3266

I agree with Raza. Definitely try to set a class on the elements you're looking for.

If that turns out to be impossible for whatever reason, here are a couple more options.

1) You could try regular expressions:

# match text that doesn't contain 'Main'
page.all('li.tab.exist', text: /^(?:(?!Main).)*$/)

That's not super easy to read. But since you've scoped your class down quite a bit, it might not be too slow.

2) Another alternative is xpath:

# find li with class of 'exist' and any text except 'Main'
page.all(:xpath, "//li[contains(@class, 'exist') and not(contains(.,'Main'))]" )

That's also a bit unweildy, especially if you want to go as in depth as your original css matcher. I'd definitely include a comment along with it.

Further info: using a css class is definitely faster and easier. Always avoid text matches whenever possible.

Upvotes: 1

Raza Hussain
Raza Hussain

Reputation: 762

Just add a class to the group of elements you want to select and the find with:

page.find('.class_name')

Upvotes: 0

Related Questions