Test if a block is passed with RSpec Mocks

sh01ch1 picture sh01ch1 · Dec 2, 2014 · Viewed 9.2k times · Source

I can test if arguments are passed like:

RSpec.describe do
  it do
    obj = double
    expect(obj).to receive(:method).with(1, 2, 3)
    obj.method(1, 2, 3)
  end
end

How should I do about a block parameter? My ideal code:

RSpec.describe do
  it do
    obj = double
    proc = Proc.new{}
    expect(obj).to receive(:method).with(1, 2, 3).with_block(proc)
    obj.method(1, 2, 3, &proc)
  end
end

Answer

sh01ch1 picture sh01ch1 · Dec 5, 2014

It seems that I cannot simply test if a block is passed with method chaining. And I found one dull answer, Block Implementation:

RSpec.describe do
  it do
    obj = double
    proc = Proc.new{}
    expect(obj).to receive(:method).with(1, 2, 3) do |*args, &block|
      expect(proc).to be(block)
    end
    obj.method(1, 2, 3, &proc)
  end
end

However, we cannot use a block implementation and other response configuration methods at the same time like receive(:method).with(1, 2, 3){|*| ...}.and_call_original.