Read more

Capybara: Quick checking for element presence (without retries or timeout)

Dominik Schöler
July 01, 2019Software engineer at makandra GmbH

Element finding is a central feature of Capybara. Since #find is normally used to get elements from the current page and interact with them, it's a good thing that some Capybara drivers (e.g. Selenium) will wait an amount of time until the expected element shows up. But if Capybara cannot #find it at all, you'll get an error.

if page.find('.that-element')
  # Do something
else
  # Never happens because #find raises
end
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

In order to simply check whether an element is present, without errors raised, you can use #has_css?. It will return a Boolean – but will wait as well. If the element does not exist, it will take the configured Capybara.default_wait_time for this check to return false, which is usually several seconds.

The solution is to disable the waiting for just that check:

if page.has_css?('.that-element', wait: 0)
  # Do something
else
  # Do something else
end

Note the wait: 0 argument. Actually there is a host of options Show archive.org snapshot worth knowing (scroll down to the "Options Hash" section).

Posted by Dominik Schöler to makandra dev (2019-07-01 15:40)