How to test that invalid arguments raise an ArgumentError exception using RSpec?
- by John Topley
I'm writing a RubyGem that can raise an ArgumentError if the arguments supplied to its single method are invalid. How can I write a test for this using RSpec?
The example below shows the sort of implementation I have in mind. The bar method expects a single boolean argument (:baz), the type of which is checked to make sure that it actually is a boolean:
module Foo
def self.bar(options = {})
baz = options.fetch(:baz, true)
validate_arguments(baz)
end
def self.validate_arguments(baz)
raise(ArgumentError, ":baz must be a boolean") unless valid_baz?(baz)
end
def self.valid_baz?(baz)
baz.is_a?(TrueClass) || baz.is_a?(FalseClass)
end
end