Capybara unable to find hidden element with text
Asked Answered
H

1

5

In my app I have a page that pops up a modal that will update some content in it and dismiss itself (and become invisible) after uncertain amount of time. In my spec, I am trying to wait until the modal dismisses. My strategy is to have Capybara wait for the content on the modal to become invisible by doing

expect(page).to have_css('.hidden-element', visible: :hidden, text: 'Hidden Content')

However, it looks like Capybara won't be able to get the text of a hidden element, and I am getting the error:

expected to find css ".hidden-element" with text "Hidden Content" but there were no matches. Also found "", which matched the selector but not all filters.

It would pass if I do :all or false, but that's not what I want:

expect(page).to have_css('.hidden-element', visible: :all, text: 'Hidden Content')

Given that I could not change my app, I wonder why that didn't work or what the best way is to achieve that in this case. Thanks!

I am using RSpec, Capybara, Capybara-webkit.

Hue answered 14/11, 2016 at 1:10 Comment(0)
B
7

If the element is actually becoming non-visible on the page, rather than being removed from the page completely, the major difference is that when visible the text is matched against visible text with the CSS applied (text-transform, etc). So if the elements text in the HTML is actually 'hidden content' but has text-transform: capitalize applied to it when visible you would need to test against the HTML form when checking non-visible elements

expect(page).to have_css('.hidden-element', visible: :hidden, text: 'hidden content')

If, on the other hand, the text in the HTML is as you show it and the element is actually removed from the page (rather than just being hidden) you can do

expect(page).not_to have_css('.hidden-element', visible: :hidden, text: 'Hidden Content')

to wait for it to be removed.

UPDATE: There is a limitation in Capybara < 2.11.0 when using the visible: :hidden option that text can't be matched. You may be able to workaround it by doing something like

element = page.find('.hidden-element', visible: :all, text: 'hidden content')
expect(element).to match_css('.hidden-element', visible: :hidden)
Bunting answered 14/11, 2016 at 2:10 Comment(3)
Thanks for suggesting! I think in my case it's not related to the case. It's not working either when the text is, for example, '1234'. I feel somehow the visible: :hidden and text: '1234' are mutually exclusive, and they work perfectly alone.Hue
@Hue What version of Capybara are you using?Bunting
@Hue After testing this It looks like this is a limitation of Capybara at the moment, when using the visible: :hidden option - I've updated my answer with a possible workaroundBunting

© 2022 - 2024 — McMap. All rights reserved.