Checking if an element exists without losing time in Capybara
automated-tests, capybara, cucumber
Solution
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?
Problem
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.