1

在下面的代码中,我想获取所有失败的列表rescue

puts "Verifying Home Page"
  begin   
    page.find('#logoAnchor')
    puts "logo anchor found"
    page.find('.navbar-inner')
    puts "Header bar found"
    page.find('.unstyled')
    puts "Found occations frame"
    page.find('#easyPrintPromoBox')
    puts "Easy Print Frame Found!"
    page.find('.tabbable')
    puts "3 Tabs  Found!"
    page.find('#givingCardPromoBox')
    puts "Create Frame Found!"
    page.find('.footer')
    puts "Footer Found!"

  rescue
    puts "Logo anchor not Found"
  end

在这里,我仅在未找到徽标锚点的情况下捕获异常。如果未找到任何异常,我必须捕获异常。例如:

如果未找到徽标锚,则将“徽标锚不存在”放入rescue
如果标题栏不存在,则将“未找到标题栏”放入rescue

4

2 回答 2

3

这是一种使用方法Array#partition

# dummy placeholder method for `page.find`
def find(el)
  if rand < 0.5
    raise :nop
  else
    true
  end
end

selectors = ['#logoAnchor', '.navbar-inner', '.unstyled', '#easyPrintPromoBox', '.tabbable', '#givingCardPromoBox', '.footer']
found, not_found = selectors.partition do |selector|
  find(selector) rescue false
end

puts "Found: #{found}"
puts "Not found: #{not_found}"

样本输出:

Found: ["#logoAnchor", ".unstyled", "#easyPrintPromoBox", ".tabbable"]
Not found: [".navbar-inner", "#givingCardPromoBox", ".footer"]

这应该在 Capybara 中工作(未测试):

selectors = ['#logoAnchor', '.navbar-inner', '.unstyled', '#easyPrintPromoBox', '.tabbable', '#givingCardPromoBox', '.footer']
found, not_found = selectors.partition do |selector|
  page.find(selector) rescue false
end

puts "Found: #{found}"
puts "Not found: #{not_found}"
于 2013-05-15T11:16:55.120 回答
1
puts "Verifying Home Page"
  begin   
    page.find('#logoAnchor')
    puts "logo anchor found"
  rescue
    puts "Logo anchor not Found"
  end

  begin   
    page.find('#navbar-inner')
    puts "navbar-inner found"
  rescue
    puts "navbar-inner not Found"
  end

  ...
  end

或者

def findOrRescue(id, successMsg, errorMsg)
   begin   
    page.find(id)
    puts successMsg
   rescue
    puts errorMsg
   end
end

 puts "Verifying Home Page"
   findOrRescue("#logoAnchor", "logo anchor found", "Logo anchor not Found")
   ...
于 2013-05-15T11:17:02.580 回答