gpt4 book ai didi

ruby - RSpec:每次指定对具有不同参数的方法的多次调用

转载 作者:数据小太阳 更新时间:2023-10-29 06:24:04 26 4
gpt4 key购买 nike

在 rspec (1.2.9) 中,指定一个对象每次都会收到对一个方法的多次调用的正确方法是什么?

我问是因为这个令人困惑的结果:

describe Object do

it "passes, as expected" do
foo = mock('foo')
foo.should_receive(:bar).once.ordered.with(1)
foo.should_receive(:bar).once.ordered.with(2)
foo.bar(1)
foo.bar(2)
end

it "fails, as expected" do
foo = mock('foo')
foo.should_receive(:bar).once.ordered.with(1) # => Mock "foo" expected :bar with (1) once, but received it twice
foo.should_receive(:bar).once.ordered.with(2)
foo.bar(1)
foo.bar(1)
foo.bar(2)
end

it "fails, as expected" do
foo = mock('foo')
foo.should_receive(:bar).once.ordered.with(1)
foo.should_receive(:bar).once.ordered.with(2)
foo.bar(2) # => Mock "foo" received :bar out of order
foo.bar(1)
end

it "fails, as expected, but with an unexpected message" do
foo = mock('foo')
foo.should_receive(:bar).once.ordered.with(1)
foo.should_receive(:bar).once.ordered.with(2)
foo.bar(1)
foo.bar(999) # => Mock "foo" received :bar with unexpected arguments
# => expected: (1)
# => got (999)
end

end

我预计最后一条失败消息是“预计:(2)”,而不是“预计 (1)”。我是否错误地使用了 rspec?

最佳答案

类似于此question .推荐的解决方案是调用as_null_object 来避免消息的混淆。所以:

describe Object do
it "fails, as expected, (using null object)" do
foo = mock('foo').as_null_object
foo.should_receive(:bar).once.ordered.with(1)
foo.should_receive(:bar).once.ordered.with(2)
foo.bar(1)
foo.bar(999) # => Mock "foo" expected :bar with (2) once, but received it 0 times
end
end

输出与您的第二种情况(即“预期 2 但得到 999”)不同,但它确实表明没有达到预期。

关于ruby - RSpec:每次指定对具有不同参数的方法的多次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1971729/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com