Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 920
ojas Avatar asked Jun 16 '17 21:06

ojas


2 Answers

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
like image 174
Stefan Avatar answered Nov 02 '22 23:11

Stefan


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
like image 43
knugie Avatar answered Nov 03 '22 01:11

knugie