Search code examples
rubyrspecruby-block

Pass a ruby &block using rspec


I want to test the functionality of the method using rspec that receives anonymous block and not raise error. Below is my code:

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 

It is below throwing error

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

Spent a lot of time browsing articles of ruby blocks and ruby documentation but can't figure out.


Solution

  • It's too complicated for no reason. Did you mean this?

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