【问题标题】:Rspec assertion doesn't make sense: Double received unexpected message with <message>Rspec 断言没有意义:双重收到带有 <message> 的意外消息
【发布时间】:2021-09-12 01:21:07
【问题描述】:

这是一个可重复性极低的示例,您可以复制它并使用最新版本的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

我认为这个测试是有道理的,但是当我运行它时,它没有说它收到了一条意外消息,该消息实际上是从实际调用中复制粘贴的。

% 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

如果重要,这里是版本。

% rspec --version
RSpec 3.10

【问题讨论】:

    标签: ruby unit-testing rspec stub rspec3


    【解决方案1】:

    哦,我想我刚刚意识到expect 必须在代码实际运行之前出现。

    #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
    

    【讨论】:

    • 是的,那个。或者您可以先allow(obj).to receive(msg),然后再expect(obj).to have_received(msg)
    • 这是更好的模式吗?
    • 取决于用例。我几乎从不使用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-26
    • 1970-01-01
    • 2018-07-03
    相关资源
    最近更新 更多