RSpec3 Mock Argument Expectation - With &block?

268 Views Asked by At

I have a method that receives a block, and delegates it to another method. Really simple:

def self.build(&block)
  Builder.build(&block)
end

I'd like RSpec (v3) to test that the received block was passed to the new method. My test currently looks like:

describe ".build" do
  it "delegates to Builder" do
    block = -> {}
    expect(App::Builder).to receive(:build).with(&block)
    described_class.build(&block)
  end
end

But RSpec is giving me an ArgumentError: `with` must have at least one argument. Use `no_args` matcher to set the expectation of receiving no arguments. Is there a way to ask RSpec to expect a method call with a specific block?

1

There are 1 best solutions below

0
On

You cannot use expectation to test that a specific block is passed. You can check that a code is run by adding code inside it, for example:

describe ".build" do
  it "delegates to Builder" do
    block_is = double('block')
    block = -> {
      block_is.run
    }

    expect(App::Builder).to receive(:build).and_yield
    expect(block_is).to receive(:run)

    described_class.build(&block)
  end
end