Checking if an element exists without losing time in Capybara
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?
When you're using #find
to decide on element presence, you should reduce the wait time for just that call:
if page.has_css?('#blabla', wait: 0)
# Do something
end
However, in your special case, the suggested solution is even better, because it saves you multiple "find" calls for the same element.