1

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.

Stefan
  • 109,145
  • 14
  • 143
  • 218
ojas
  • 2,150
  • 5
  • 22
  • 37

1 Answers1

2

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  
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
  • yes i can do it like this but my motive is to pass a block to a function using rspec – ojas Jun 16 '17 at 17:36
  • @OJASJUNEJA: what would you hope to accomplish with that? – Sergio Tulentsev Jun 16 '17 at 17:37
  • 1
    @OJASJUNEJA you can't pass anything with rspec. The `expect to receive` construct only sets an expectation. And you can get/call a block that was passed to you. But the actual invocation must be done by "regular ruby". – Sergio Tulentsev Jun 16 '17 at 17:40
  • Actually it is just a demo of my real work. I cant post it here. I have function which takes &block as parameter and call that block in its definition. I know how to write rspec test case. I am just not able to pass a block to a function using rspec – ojas Jun 16 '17 at 17:40
  • but we have rspec receive(:method).with()... source:https://relishapp.com/rspec/rspec-mocks/v/3-2/docs/setting-constraints/matching-arguments – ojas Jun 16 '17 at 17:45
  • @OJASJUNEJA: Yes, and that is not calling/passing anything. – Sergio Tulentsev Jun 16 '17 at 17:57