0

I'm trying to write a simple rspec test for bitly raise error exception. How can I write the expect to match the error message ALREADY_A_BITLY_LINK - '500' with the raise_error(BitlyError). This rspec actually pass. But if I were to use the same raise_error for invalid URL. It will also pass. How can I test the specific exception message?

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

Debugger

@bitly.shorten(bitly_url) returns *** BitlyError Exception: ALREADY_A_BITLY_LINK - '500'

raise_error(BitlyError) returns #<RSpec::Matchers::BuiltIn::RaiseError:0x007fa229c56f48 @block=nil, @actual_error=nil, @warn_about_bare_error=false, @expected_error=BitlyError, @expected_message=nil>

khoamle
  • 676
  • 2
  • 7
  • 21

1 Answers1

1

As you can see from the docs - https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers/raise-error-matcher - the raise error matcher can take a second parameter of string or regex to match against the exceptions message

expect { whatever }.to raise_error(BitlyError, "ALREADY_A_BITLY_LINK")
Thomas Walpole
  • 48,548
  • 5
  • 64
  • 78