在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

输出与您的第二个 case (即"预期2但得到999")不同,但它确实表明未达到预期.

Ruby相关问答推荐

根据部分已知值判断数组内容的简洁 Rubyist 方法是什么?

在Ruby中按字母顺序对数组中的数组进行排序?

将数组转换 for each 元素的嵌套哈希

如果 Java 人go Scala,C# go F#,那么 Ruby 人go 哪里寻求函数式?

以编程方式获得完整的 Ruby 版本?

检测 ruby​​ 是否在 Windows 上运行的正确方法是什么?

在 Go (golang) 中编写一个 Ruby 扩展

`expect`测试中的Rspec`eq`与`eql`

ruby:对两个或多个数组的对应成员求和

为什么 Matz Select 在 Ruby 中默认使字符串可变?

在文件中搜索字符串的最佳方法是什么?

Rails 在最后一个之前加入逗号和and的字符串列表

理解|| Ruby 中 If 条件中的 OR 运算符

Ruby Koans 的 test_sharing_hashes 中的附加问题的答案是什么?

将整个文本文件作为单个字符串读取的合理方法是什么?

为什么 __FILE__ 大写而 __dir__ 小写?

如何在 macOS 上卸载 rbenv?

为什么在安装 gem 时出现权限被拒绝错误?

Ruby:如何为数组和哈希制作 IRB 打印 struct

=== 与 == 在 Ruby 中