RSpec:在方法内调用外部对象的stub方法

时间:2012-08-27 20:36:00

标签: 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

规格:

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

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

提前感谢任何想法!

1 个答案:

答案 0 :(得分:4)

你必须存根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

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