Rspec 断言没有意义:双重收到 <message> 的意外消息
Rspec assertion doesn't make sense: Double received unexpected message with <message>
这是一个可重现性极低的示例,您只需复制它,然后 运行 使用最新版本的 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
哦,我想我刚刚意识到 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
这是一个可重现性极低的示例,您只需复制它,然后 运行 使用最新版本的 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
哦,我想我刚刚意识到 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