使用 rspec 传递 ruby &block

Pass a ruby &block using rspec

我想测试使用 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 文档的文章,但无法弄清楚。

无缘无故的太复杂了。你是这个意思吗?

it "testing speak functionality not to raise error" do
  sp = SP.new
  expect {
    sp.speak {raise StandardError}
  }.to_not raise_error
end