RSpec: calling a stub method for an external object inside a method

I am trying to drown the behavior of a method in a method:

class A def method_one(an_argument) begin external_obj = ExternalThing.new result = external_obj.ext_method(an_argument) rescue Exception => e logger.info(e.message) end end end 

Spec:

 it "should raise an Exception when passed a bad argument" do a = A.new external_mock = mock('external_obj') external_mock.stub(:ext_method).and_raise(Exception) expect { a.method_one("bad") }.to raise_exception end 

However, an exception never rises.

I also tried:

 it "should raise an Exception when passed a bad argument" do a = A.new a.stub(:ext_method).and_raise(Exception) expect { a.method_one("bad") }.to raise_exception end 

and it doesn’t work either. How can I properly mute an external method to force an exception in this case?

Thanks in advance for any ideas!

+4
source share
1 answer

You must stub the new class method from ExternalThing and make it return mock:

 it "should raise an Exception when passed a bad argument" do a = A.new external_obj = mock('external_obj') ExternalThing.stub(:new) { external_obj } external_obj.should_receive(:ext_method).and_raise(Exception) expect { a.method_one("bad") }.to raise_exception end 

Note that this solution is deprecated in rspec 3. For a solution that is not deprecated in rspec 3, see rspec 3 - override the class method .

+4
source

All Articles