0

ruby/rspec 新手并尝试测试方法是否引发异常。我可能完全不正确地解决这个问题。

#require 'rspec'

describe "TestClass" do
  it "should raise exception when my method is called" do
    test = Test.new
    test.should_receive(:my_method).and_raise
  end
end

class Test
  def my_method
    raise
  end
end  


rspec test.rb
F

Failures:

  1) TestClass should raise exception when my method is called
     Failure/Error: test.should_receive(:my_method).and_raise
       (#<Test:0x007fc61c82f7c8>).my_method(any args)
           expected: 1 time
           received: 0 times
     # ./test.rb:6:in `block (2 levels) in <top (required)>'

Finished in 0.00061 seconds
1 example, 1 failure

Failed examples:

rspec ./test.rb:4 # TestClass should raise exception when my method is called

为什么消息收到零次?

4

2 回答 2

1

你的测试是错误的。为了测试是否引发了异常,您需要执行以下操作:

it "should raise exception when my method is called" do
  test = Test.new
  test.should_receive(:my_method)

  expect {
    test.my_method
  }.to raise_error      
end

在这种情况下,您可能不需要添加should_receive. 通过调用my_method您确保test正在接收该方法。基本上,当您不需要嘲笑时,您就是在嘲笑。

于 2013-03-01T20:42:51.257 回答
0

您必须做一些事情来调用该方法。如果是回调,这里是如何测试它们的示例。

于 2013-03-01T20:34:24.637 回答