2015-10-14 97 views
2

最近我一直在使用機械寶石,並且希望加入一些測試以確保我能夠捕捉到適當的錯誤。什麼是測試錯誤處理的正確方法?測試錯誤處理的正確方法是什麼?

這是我的基本方法:

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

的排序。您不應該在應用程序中再次測試依賴庫。只要抓住Net :: HTTP :: Persistent :: Error而不確保底層功能正常就足夠了。寫得好的寶石應該提供他們自己的測試,並且你應該能夠通過測試那個寶石(例如機械化)來根據需要訪問這些測試。

你可以嘲笑這些錯誤,但你應該是明智的。下面是一些代碼來嘲笑的SMTP連接

class Mock 
    require 'net/smtp' 

    def initialize(options) 
     @options = options 
     @username = options[:username] 
     @password = options[:password] 
     options[:port] ? @port = options[:port] : @port = 25 
     @helo_domain = options[:helo_domain] 
     @from_addr = options[:from_address] 
     @from_domain = options[:from_domain] 

     #Mock object for SMTP connections 
     mock_config = {} 
     mock_config[:address] = options[:server] 
     mock_config[:port] = @port 

     @connection = RSpec::instance_double(Net::SMTP, mock_config) 

     allow(@connection).to receive(:start).and_yield(@connection) 
     allow(@connection).to receive(:send_message).and_return(true) 
     allow(@connection).to receive(:started?).and_return(true) 
     allow(@connection).to receive(:finish).and_return(true) 
    end 
    #more stuff here 
end 

我沒有看到你的任何自定義錯誤這將使更多的意義在這裏測試。例如,您可能會測試參數中的URL不友好字符並從中解救。在那種情況下,你的測試會提供一些明確的東西。

expect(get("???.net")).to raise_error(CustomError) 
+2

哈哈,答案編輯之前我打-1 – akostadinov

+0

@jjk謝謝您回答。這種情況的一些背景是我的抓取工具在過去已經獲得了所有類型的錯誤,無論是試圖訪問一個不存在的頁面或僅僅是連接超時。機械化會適當地引起每個錯誤,我想測試處理。 – binarymason

+1

所以如果你需要明確的話,你會創建一個依賴於每個基礎對象的模擬對象。然後你可以處理他們被提出,或任何其他。您注意到我正在使用rspec的實例double創建一個我可以使用的接口。然後我可以在我的模擬對象的實例中引用它。如果這有幫助,請將此答案標爲正確。 – jjk

1

您需要mockMechanize類。搜索其他問題怎麼辦

相關問題