Skip to content

Commit

Permalink
More detailed error message when and_raise gets a class whose constru…
Browse files Browse the repository at this point in the history
…ctor requires 1 or more args.

- #99, #100.
  • Loading branch information
dchelimsky committed Jan 30, 2012
1 parent 7ce8c6f commit 1f28dcd
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
9 changes: 6 additions & 3 deletions lib/rspec/mocks/message_expectation.rb
Expand Up @@ -179,9 +179,12 @@ def invoke(*args, &block)

begin
begin
Kernel::raise(@exception_to_raise) unless @exception_to_raise.nil?
rescue ArgumentError => ex
Kernel::raise ex.exception("Errors raised by expectations cannot have constructors that take arguments. #{@exception_to_raise.to_s} has a constructor requiring #{@exception_to_raise.instance_method(:initialize).arity}.")
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
Kernel::throw(*@args_to_throw) unless @args_to_throw.empty?

Expand Down
8 changes: 4 additions & 4 deletions spec/rspec/mocks/mock_spec.rb
Expand Up @@ -216,16 +216,16 @@ def @mock.method_with_default_argument(arg={}); end
}.should raise_error(RuntimeError, "error message")
end

it "fails with nice message if passed Exception requires constructor arguments" do
class ErrorThatHasAConstructorTakingArguments < RuntimeError
it "fails with helpful message if submitted Exception requires constructor arguments" do
class ErrorWithNonZeroArgConstructor < RuntimeError
def initialize(i_take_an_argument)
end
end

@mock.should_receive(:something).and_raise(ErrorThatHasAConstructorTakingArguments)
@mock.stub(:something).and_raise(ErrorWithNonZeroArgConstructor)
lambda {
@mock.something
}.should raise_error(ArgumentError, "Errors raised by expectations cannot have constructors that take arguments. RSpec::Mocks::ErrorThatHasAConstructorTakingArguments has a constructor requiring 1.")
}.should raise_error(ArgumentError, /^'and_raise' can only accept an Exception class if an instance/)
end

it "raises RuntimeError with passed message" do
Expand Down

0 comments on commit 1f28dcd

Please sign in to comment.