rubyunit-testingrspecstubrspec3

Rspec assertion doesn't make sense: Double received unexpected message with <message>


Here's a minimally reproducible example, you can just copy this and run it with the latest version of gem install rspec.

#class Bar
#  def run_bar(a:, b:)
#    return
#  end
#end

def foo(bar)
  if bar != nil
    bar.run_bar(a: "test", b: {})
  end
end

describe 'foo' do
  it 'runs bar' do
    bar_stub = double('bar')
    foo(bar_stub)
    expect(bar_stub).to receive(:run_bar).with(a: "test", b: {})
  end
end

I think this test makes sense but when I run it, it fails saying it got an unexpected message which is quite literally copy-pasted from the actual invocation.

% rspec test.rb
F

Failures:

  1) foo runs bar
     Failure/Error: bar.run_bar(a: "test", b: {})
       #<Double "bar"> received unexpected message :run_bar with ({:a=>"test", :b=>{}})
     # ./test.rb:9:in `foo'
     # ./test.rb:16:in `block (2 levels) in <top (required)>'

Finished in 0.00812 seconds (files took 0.09453 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./test.rb:14 # foo runs bar

If it matters, here's the version.

% rspec --version
RSpec 3.10

Solution

  • Oh, I think I just realized that the expect has to come before the code is actually run.

    #class Bar
    #  def run_bar(a:, b:)
    #    return
    #  end
    #end
    
    def foo(bar)
      if bar != nil
        bar.run_bar(a: "test", b: {})
      end
    end
    
    describe 'foo' do
      it 'runs bar' do
        bar_stub = double('bar')
        expect(bar_stub).to receive(:run_bar).with(a: "test", b: {})
        foo(bar_stub)
      end
    end