TangibleDream TangibleDream - 7 days ago 5
Ruby Question

How do I create designer exceptions when a find fails to find an element?

I'd like to make a custom error message when I fail to find an element...

if find(:xpath, '*[@id="broken_path"]/div/a') == nil #or false?
raise 'designer error message'
end


Do I need to try and catch?

Answer

Capybaras find either returns the element or raises an exception. To catch that you'd need to use rescue

def find_my_element
  find(:xpath, '*[@id="broken_path"]/div/a')
rescue Capybara::ElementNotFound
  raise 'designer error message'
end

Note that if you call a method like this inside a within block (or any other synchronized Capybara block) it may defeat some of the waiting/retrying behavior since Capybara expects to see the ElementNotFound error. You may be better off registering your own selector which allows you to specify your own description which will get returned in the message of the Capybara::ElementNotFound (See - https://github.com/teamcapybara/capybara/blob/master/lib/capybara/selector.rb#L67 - for the Capybara provided selectors as examples)

Capybara.add_selector(:my_selector) do
  xpath { |_unused| '*[@id="broken_path"]/div/a' }
  # could also be written as
  # css { |_unused| '#broken_path div a' }
  describe do |_options|
    "my description"
  end
end

find(:my_selector)
Comments