Search code examples
rubyrspecruby-block

How to check block is called using rspec


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.


Solution

  • 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