1

我想使用接收匿名块且不引发错误的 rspec 来测试该方法的功能。下面是我的代码:

class SP
  def speak(options={},&block)
    puts "speak called" 
    block.call()
  rescue StandardError => e
    puts e.inspect()
  end  
end


describe SP do
  it "testing speak functionality not to raise error" do
    sp = SP.new
    sp_mock = double(sp)
    expect(sp_mock).to receive(:speak).with(sp.speak{raise StandardError}).not_to raise_error
  end  
end 

它低于抛出错误

SP testing speak functionality not to raise error

 Failure/Error: expect(sp).to receive(:speak).with(sp.speak{raise StandardError})

   (#<SP:0x007fead2081d20>).speak(nil)
       expected: 1 time with arguments: (nil)
       received: 0 times
 # ./test.rb:22:in `block (2 levels) in <top (required)>'

花了很多时间浏览 ruby​​ 块和 ruby​​ 文档的文章,但无法弄清楚。

4

1 回答 1

2

这太复杂了,没有任何理由。你是这个意思吗?

it "testing speak functionality not to raise error" do
  sp = SP.new
  expect {
    sp.speak {raise StandardError}
  }.to_not raise_error
end  
于 2017-06-16T17:30:25.497 回答