How to test that invalid arguments raise an ArgumentError exception using RSpec?

Posted by John Topley on Stack Overflow See other posts from Stack Overflow or by John Topley
Published on 2010-05-16T09:54:03Z Indexed on 2010/05/16 10:00 UTC
Read the original article Hit count: 154

Filed under:
|

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

© Stack Overflow or respective owner

Related posts about rspec

Related posts about ruby