最近我一直在使用機械寶石,並且希望加入一些測試以確保我能夠捕捉到適當的錯誤。什麼是測試錯誤處理的正確方法?測試錯誤處理的正確方法是什麼?
這是我的基本方法:
def get(str)
url = format_url(str)
#puts "sending GET request to: #{url}"
sleep(0.1)
@page = Mechanize.new do |a|
a.user_agent_alias = 'Mac Safari'
a.open_timeout = 7
a.read_timeout = 7
a.idle_timeout = 7
a.redirect_ok = true
end.get(url)
rescue Mechanize::ResponseCodeError => e
puts "#{'Response Error:'.red} #{e}"
rescue SocketError => e
puts "#{'Socket Error:'.red} #{e}"
rescue Net::OpenTimeout => e
puts "#{'Connection Timeout:'.red} #{e}"
rescue Errno::ETIMEDOUT => e
puts "#{'Connection Timeout:'.red} #{e}"
rescue Net::HTTP::Persistent::Error
puts "#{'Connection Timeout:'.red} read timeout, too many resets."
end
這是開始試驗處理錯誤:
class TestErrorHandling < Mechanize::TestCase
context 'Example when sending a GET request' do
should 'rescue error and return nil' do
assert_equal nil, Example.get('http://localhost/pagethatdoesntexist')
end
end
end
我在正確的方向前進嗎?任何見解和/或資源的歡迎。
哈哈,答案編輯之前我打-1 – akostadinov
@jjk謝謝您回答。這種情況的一些背景是我的抓取工具在過去已經獲得了所有類型的錯誤,無論是試圖訪問一個不存在的頁面或僅僅是連接超時。機械化會適當地引起每個錯誤,我想測試處理。 – binarymason
所以如果你需要明確的話,你會創建一個依賴於每個基礎對象的模擬對象。然後你可以處理他們被提出,或任何其他。您注意到我正在使用rspec的實例double創建一個我可以使用的接口。然後我可以在我的模擬對象的實例中引用它。如果這有幫助,請將此答案標爲正確。 – jjk