如何使用 rspec 调用检查块

How to check block is called using rspec

我想检查是否使用 rspec 在我的函数中调用了该块。下面是我的代码:

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




describe SP do
 it "testing speak functionality can receive a block" do
    sp = SP.new
    def test_func 
        a = 1
    end
    sp_mock = double(sp)
    expect(sp_mock).to receive(:speak).with(test_func)
    sp.speak(test_func)
 end  
end 

以下是我的错误:

SP testing speak functionality can receive a block
     Failure/Error: block.call()

     NoMethodError:
       undefined method `call' for nil:NilClass
     # ./test.rb:9:in `speak'
     # ./test.rb:25:in `block (2 levels) in <top (required)>'

你能帮忙吗。我花了很多时间。

您必须使用 RSpec 之一 yield matcher:

describe SP do
  it "testing speak functionality can receive a block" do
    sp = SP.new
    expect { |b| sp.speak(&b) }.to yield_control
  end
end

我认为 Stefan 提供了最佳答案。但是我想指出,您应该测试代码的行为而不是实现细节。

describe SP do
  it "testing speak functionality can receive a block" do
    sp = SP.new
    called = false
    test_func = -> () { called = true }

    sp.speak(&test_func)

    expect(called).to eql(true)
  end  
end