5

我试图在方法中存根方法的行为:

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

规格:

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

但是,永远不会引发异常。

我也试过:

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

这也不起作用。在这种情况下,如何正确地存根外部方法以强制异常?

提前感谢您的任何想法!

4

1 回答 1

4

您必须存根的类方法newExternalThing使其返回模拟:

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

请注意,此解决方案在 rspec 3 中已弃用。对于未在 rspec 3 中弃用的解决方案,请参阅rspec 3 - stub a class method

于 2012-08-27T21:45:16.007 回答