bitly引发错误异常rspec测试
问题描述:
我正在尝试编写一个简单的rspec测试,用于引发错误异常。我如何编写期望值以便将错误消息ALREADY_A_BITLY_LINK - '500'
与raise_error(BitlyError)
相匹配。这rspec实际上通过。但是,如果我将相同的raise_error用于无效的URL。它也会通过。我如何测试特定的异常消息?bitly引发错误异常rspec测试
bitly_spec.rb
require 'rails_helper'
describe Bitly do
before do
@bitly = Bitly.new(username, api_key)
end
let(:bitly_url) { 'bitly_url' } #stackoverflow doesn't allow URL shortener
it 'should return exception error if given url is bitly' do
expect { @bitly.shorten(bitly_url) }.to raise_error(BitlyError)
end
end
调试
@bitly.shorten(bitly_url)
回报*** BitlyError Exception: ALREADY_A_BITLY_LINK - '500'
raise_error(BitlyError)
回报#<RSpec::Matchers::BuiltIn::RaiseError:0x007fa229c56f48 @block=nil, @actual_error=nil, @warn_about_bare_error=false, @expected_error=BitlyError, @expected_message=nil>
答
你可以从文档看 - https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers/raise-error-matcher - 加薪错误匹配可以采取字符串或正则表达式的第二个参数匹配例外消息
expect { whatever }.to raise_error(BitlyError, "ALREADY_A_BITLY_LINK")