Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if an element exists without losing time in Capybara

I like to keep things DRY, that's why I want to have the following in one of my steps:

if first(:css, "#blabla") != nil
    find_by_id(blabla).click
end
find_by_id(....)
....

This means, that it will look for a certain element, and if it exists, it will click on it. If not, I will not lose time (my default wait time is 20 secs, which will be used if I put find instead of first there.

The main issue is that I don't want to lose time when checking for a certain element in this case, but I am also wondering if this is a good approach.

like image 987
TrashyMcTrash Avatar asked Mar 21 '13 20:03

TrashyMcTrash


1 Answers

I see the issue that your code does unnecessary second query to browser (you already have first(:css, "#blabla") so no need to do find_by_id(blabla))

I propose you to find element using one query:

el = first('#blabla')
el.click unless el.nil?

Note that there is no losing time here as first doesn't block.

However, first doesn't check that there no other elements on the page. You can add :maximum to check it:

el = first('#blabla', maximum: 1)
el.click unless el.nil?
like image 134
Andrei Botalov Avatar answered Oct 19 '22 04:10

Andrei Botalov