我最近一直在使用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
我走的方向对吗?欢迎提供任何见解和/或资源。
这是我找到更符合我所问的答案的链接: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
有点。不应该在应用程序中再次测试依赖库。捕获Net::HTTP::Persistent::Error就足够了,无需确保底层功能正常工作。编写良好的gem应该提供它们自己的测试,并且您应该能够根据需要通过测试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不友好的字符,并从中进行挽救。在这种情况下,您的测试将提供一些明确的内容。
expect(get("???.net")).to raise_error(CustomError)
您需要mock
Mechanize
类。搜索其他问题如何做