简体   繁体   中英

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.

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  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM