什么是测试错误处理的正确方法?

时间:2015-10-14 19:34:07

标签: ruby error-handling tdd mechanize-ruby

我最近一直在使用Mechanize gem,并希望合并一些测试以确保我捕获正确的错误。测试错误处理的正确方法是什么?

这是我的基本方法:

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

我是朝着正确的方向前进吗?欢迎任何见解和/或资源。

3 个答案:

答案 0 :(得分:2)

这是我找到更符合我要求的答案的链接: https://stackoverflow.com/a/17825110/5381605

describe 'testing' do
  it 'must raise' do
   a = Proc.new {oo.non_existant}
   begin
     a[]
   rescue => e
    end
   e.must_be_kind_of Exception
  end
end

答案 1 :(得分:1)

您需要mock Mechanize课程。搜索其他问题怎么做

答案 2 :(得分:1)

排序。您不应该在应用程序中再次测试依赖库 。它足以捕获Net :: HTTP :: Persistent :: Error而不确保底层功能正常工作。写得好的宝石应该提供自己的测试,你应该能够通过测试那个gem(例如,Mechanize)来根据需要访问这些测试。

你可以嘲笑这些错误,但你应该明智。以下是模拟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-unfriendly字符并从中进行救援。在这种情况下,您的测试将提供明确的内容。

 expect(get("???.net")).to raise_error(CustomError)
相关问题