Skip to content

Instantly share code, notes, and snippets.

@erwanlr
Created July 3, 2015 11:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erwanlr/60c3d7ceee600e88ba96 to your computer and use it in GitHub Desktop.
Save erwanlr/60c3d7ceee600e88ba96 to your computer and use it in GitHub Desktop.
require 'rspec'
require 'optparse'
module Test
class Error < StandardError
end
class AnotherError < Error
def to_s
'this message exactly'
end
end
end
RSpec.describe 'matching error message with string' do
it 'matches the error message' do
expect { raise StandardError, 'this message exactly'}.
to raise_error(StandardError, 'this message exactly')
end
it 'matches the error message' do
expect { raise Test::Error, 'this message exactly' }.
to raise_error(Test::Error, 'this message exactly')
end
it 'matches the error message' do
expect { raise Test::AnotherError }.
to raise_error(Test::AnotherError, 'this message exactly')
end
it 'matches the error message, but does not :x' do
expect { raise OptionParser::InvalidArgument, 'this message exactly'}.
to raise_error(OptionParser::InvalidArgument, 'this message exactly')
end
end
@erwanlr
Copy link
Author

erwanlr commented Jul 3, 2015

Reason of the fail:

# optparse.rb L1837-1846

   def inspect
      "#<#{self.class}: #{args.join(' ')}>"
    end

    #
    # Default stringizing method to emit standard error message.
    #
    def message
      reason + ': ' + args.join(' ')
    end

The @Reason (freezed string) is added to the message but the inspect don't have it, resulting in the error below when running spec:

expected OptionParser::InvalidArgument with "this message exactly", got #<OptionParser::InvalidArgument: this message exactly>

Which is a WTF situation and should be (if #inspect was displaying the #message instead of just the args):

expected OptionParser::InvalidArgument with "this message exactly", got #<OptionParser::InvalidArgument: invalid argument: this message exactly>

So the spec should be .to raise_error(OptionParser::InvalidArgument, 'invalid argument: this message exactly')which is not really that good :x

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment