How to check block is called using rspec

那年仲夏 提交于 2021-01-28 00:29:09

问题


I want to check whether the block is called in my function using rspec. Below is my code:

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 

Below is my error:

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)>'

Could you please help. I spent lots of time in that.


回答1:


You have to use one of RSpec's 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



回答2:


I think Stefan provided the best answer. However I wanted to point out that you should be testing the behaviour of the code instead of implementation details.

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


来源:https://stackoverflow.com/questions/44598091/how-to-check-block-is-called-using-rspec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!