Sly*_*Sly 5 rspec mocking stub
我试图在方法中存根方法的行为:
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
Run Code Online (Sandbox Code Playgroud)
规格:
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
Run Code Online (Sandbox Code Playgroud)
但是,永远不会引发异常。
我也试过:
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
Run Code Online (Sandbox Code Playgroud)
这也不起作用。在这种情况下,如何正确存根外部方法以强制异常?
提前感谢您的任何想法!
您必须存根new的类方法ExternalThing并使其返回模拟:
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
Run Code Online (Sandbox Code Playgroud)
请注意,此解决方案在 rspec 3 中已弃用。有关 rspec 3 中未弃用的解决方案,请参阅rspec 3 - 存根类方法。