【问题标题】:bitly raise error exception rspec testbitly 引发错误异常 rspec 测试
【发布时间】:2016-07-16 00:38:34
【问题描述】:

我正在尝试为 bitly raise 错误异常编写一个简单的 rspec 测试。如何编写期望以将错误消息ALREADY_A_BITLY_LINK - '500'raise_error(BitlyError) 匹配。这个 rspec 实际上通过了。但是,如果我对无效 URL 使用相同的 raise_error。也会过去的。如何测试特定的异常消息?

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>

【问题讨论】:

    标签: ruby-on-rails ruby rspec capybara bit.ly


    【解决方案1】:

    正如您从文档中看到的 - https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers/raise-error-matcher - raise 错误匹配器可以采用字符串或正则表达式的第二个参数来匹配异常消息

    expect { whatever }.to raise_error(BitlyError, "ALREADY_A_BITLY_LINK")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-28
      • 2014-04-04
      • 1970-01-01
      • 2019-03-12
      • 2021-05-08
      • 2019-03-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多