← back to articles

Switch off Capybara::ElementNotFound / avoid nested rescue

Save article ToRead Archive Delete · Log out

1 min read · View original · stackoverflow.com

I've got an issue with a method shared across a wide number of integration tests.

The problem is, I need to find one of two buttons, and have so far only come up with the following unwieldy syntax for avoiding Capybara's ElementNotFound error:

new_button = begin
      find(".button_one")
    rescue Capybara::ElementNotFound
      begin
        find('.button_two')
      rescue Capybara::ElementNotFound
        raise Capybara::ElementNotFound, "Missing Button"
      end
    end
new_button.click

This works as expected: if the first button's not found, the second one is, and they're clicked. If neither are present, the error is raised.

Despite this, I really don't like the nested rescues and would like to tidy this up.

The simplest solution which feels like it should exist, though I've not found this anywhere: does anyone know if there's an option to return nil in Capybara's find method, rather than raising the exception?

For example, the following pseudocode...

new_button = find('.button_one', allow_nil: true) || find('.button_two', allow_nil: true)
new_button ? new_button.click : raise(Capybara::ElementNotFound, "Missing Button")

...would be perfect.

Otherwise, any suggestion of how best to rescue the two errors and avoid the horrible nested rescue?


Footnote: this code exists within a large existing structure, which previously worked fine where it shouldn't have. Fixing another issue has caused this problem, which is used widely throughout the suite. I'd love to adjust the calls and use the correct elements (and so avoid this altogether), though that's going to be a big project a little later in the day.