Skip to content
Browse files

and_raise should support intentionally raising an ArgumentError

  • Loading branch information...
1 parent af3f296 commit 38ddf48e71cbe3216d70e8521c5b10b0bbc97046 @maeve maeve committed
Showing with 22 additions and 8 deletions.
  1. +14 −8 lib/rspec/mocks/message_expectation.rb
  2. +8 −0 spec/rspec/mocks/mock_spec.rb
View
22 lib/rspec/mocks/message_expectation.rb
@@ -179,14 +179,7 @@ def invoke(*args, &block)
@order_group.handle_order_constraint self
begin
- begin
- raise(@exception_to_raise) unless @exception_to_raise.nil?
- rescue ArgumentError => e
- raise e.exception(<<-MESSAGE)
-'and_raise' can only accept an Exception class if an instance can be constructed with no arguments.
-#{@exception_to_raise.to_s}'s initialize method requires #{@exception_to_raise.instance_method(:initialize).arity} arguments, so you have to supply an instance instead.
-MESSAGE
- end
+ raise_exception unless @exception_to_raise.nil?
Kernel::throw(*@args_to_throw) unless @args_to_throw.empty?
default_return_val = if !@method_block.nil?
@@ -210,6 +203,19 @@ def invoke(*args, &block)
end
# @private
+ def raise_exception
+ if !@exception_to_raise.respond_to?(:instance_method) ||
+ @exception_to_raise.instance_method(:initialize).arity <= 0
+ raise(@exception_to_raise)
+ else
+ raise ArgumentError.new(<<-MESSAGE)
+'and_raise' can only accept an Exception class if an instance can be constructed with no arguments.
+#{@exception_to_raise.to_s}'s initialize method requires #{@exception_to_raise.instance_method(:initialize).arity} arguments, so you have to supply an instance instead.
+MESSAGE
+ end
+ end
+
+ # @private
def called_max_times?
@expected_received_count != :any && @expected_received_count > 0 &&
@actual_received_count >= @expected_received_count
View
8 spec/rspec/mocks/mock_spec.rb
@@ -217,6 +217,14 @@ def @mock.method_with_default_argument(arg={}); end
}.should raise_error(RuntimeError, "error message")
end
+ it "raises instance of submitted ArgumentError" do
+ error = ArgumentError.new("error message")
+ @mock.should_receive(:something).and_raise(error)
+ lambda {
+ @mock.something
+ }.should raise_error(ArgumentError, "error message")
+ end
+
it "fails with helpful message if submitted Exception requires constructor arguments" do
class ErrorWithNonZeroArgConstructor < RuntimeError
def initialize(i_take_an_argument)

0 comments on commit 38ddf48

Please sign in to comment.
Something went wrong with that request. Please try again.