当查找未能找到元素时,如何创建设计器异常?
How do I create designer exceptions when a find fails to find an element?
我想在找不到元素时生成自定义错误消息...
if find(:xpath, '*[@id="broken_path"]/div/a') == nil #or false?
raise 'designer error message'
end
我需要尝试捕捉吗?
只做你自己的例外class:
class MyFancyException < StandardError
end
那么你可以raise
它:
raise MyFancyException, "Fancy error message"
在 Ruby 中不需要 try
/catch
。你使用 rescue
:
def example
do_stuff
rescue MyFancyException => e
# e contains exception with message
end
Capybaras find
returns 元素或引发异常。要抓住它,你需要使用 rescue
def find_my_element
find(:xpath, '*[@id="broken_path"]/div/a')
rescue Capybara::ElementNotFound
raise 'designer error message'
end
请注意,如果您在 within
块(或任何其他同步的 Capybara 块)中调用这样的方法,它可能会破坏某些 waiting/retrying 行为,因为 Capybara 期望看到 ElementNotFound 错误.您最好注册自己的选择器,它允许您指定自己的描述,该描述将在 Capybara::ElementNotFound 的消息中返回(请参阅 - https://github.com/teamcapybara/capybara/blob/master/lib/capybara/selector.rb#L67 - 以 Capybara 提供的选择器为例)
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)
我想在找不到元素时生成自定义错误消息...
if find(:xpath, '*[@id="broken_path"]/div/a') == nil #or false?
raise 'designer error message'
end
我需要尝试捕捉吗?
只做你自己的例外class:
class MyFancyException < StandardError
end
那么你可以raise
它:
raise MyFancyException, "Fancy error message"
在 Ruby 中不需要 try
/catch
。你使用 rescue
:
def example
do_stuff
rescue MyFancyException => e
# e contains exception with message
end
Capybaras find
returns 元素或引发异常。要抓住它,你需要使用 rescue
def find_my_element
find(:xpath, '*[@id="broken_path"]/div/a')
rescue Capybara::ElementNotFound
raise 'designer error message'
end
请注意,如果您在 within
块(或任何其他同步的 Capybara 块)中调用这样的方法,它可能会破坏某些 waiting/retrying 行为,因为 Capybara 期望看到 ElementNotFound 错误.您最好注册自己的选择器,它允许您指定自己的描述,该描述将在 Capybara::ElementNotFound 的消息中返回(请参阅 - https://github.com/teamcapybara/capybara/blob/master/lib/capybara/selector.rb#L67 - 以 Capybara 提供的选择器为例)
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)