I am studying automated tests with capybara
, cucumber
and webdriver
I'm doing tests with expect, and I usually use expect(page).to have_selector('p', 'some cool text')
to find an element, but sometimes it happens to have more than one similar selector, and sometimes it ends up being loaded after a while.
To simplify what I'm trying to say I'm going to put together a html scheme to demonstrate what I'm trying to find.
setTimeout(function(){
document.getElementById('alpha').innerHTML = 'some cool text';
},3000)
<p style="background: rgba(255,0,0,0.1)">This text will load
<p id="alpha">Text to load after 3s</p>
<p style="background: rgba(255,0,0,0.1)">similar text that I don't want to find</p>
<p>some cool text</p>
I needed to know how to select only the first text to validate that the word 'some cool text'
was loaded, adding id or classes are welcome
The statement you've written doesn't do what you're expecting because you're just passing 'some cool text' as a parameter rather than as the text option. What you want instead is
expect(page).to have_selector('p#alpha', text: 'some cool text')
which will wait up to Capybara.default_max_wait_time
seconds for a p element with id of 'alpha' containing the text 'some cool text' to appear. By default Capybara.default_max_wait_time
is 2 seconds, so if you have a lot of things taking 3+ seconds to occur on your page you may want to increase that. If it's only this one you can extend the maximum wait for a specific call by passwing the wait
option
expect(page).to have_selector('p#alpha', text: 'some cool text', wait: 5)
Also - if I were you I'd use have_css
rather than have_selector
when you know you're using CSS
expect(page).to have_css('p#alpha', text: 'some cool text', wait: 5)