ruby - RSpec should_receive( :send). with(...): colored diff

标签 ruby unit-testing testing rspec

我正在大量使用 RSpecs 2.13 should_receive(:send).with(...) 功能。我知道这是一个过时的版本,但我必须将它用于一个项目(而且测试套件很大)。

当规范失败时,我会得到这样的差异输出:

<FooBar (class)> received :send with unexpected arguments
         expected: ({ :foo => bar, :test => "hello"})
         got: ({ :foo => bar, :test => "Hello"})

上面的论点都只是例子。我的问题是,如果我传递给 :send 的哈希值真的很长,就很难找出哪里出了问题。我为 RSpec 启用了彩色输出,但这只会将失败的测试着色为红色。

Is there a way to get a colored diff output for should_receive?

不久前,我编写了自己的匹配器 be_matching,它具有彩色差异输出:

RSpec::Matchers.define :be_matching do |expected|
  match do |actual|
    actual == expected
  end

  failure_message_for_should do |actual|
    difference = DiffMatcher::Difference.new(expected, actual, :color_enabled=>RSpec::configuration.color_enabled?)
    difference.to_s
  end
end

但是重写所有使用 should_receive 语法的测试以使用自定义匹配器需要大量工作。

是否有内置的 gem 或重新定义 should_receive 的方法,以便为失败的测试提供一些彩色差异输出?

编辑:

我找到了一个解决方法,它可以产生更好的差异输出。您可以使用如下代码块调用 should_receive:

  FooBar.should_receive(:send) do |arg1|
    arg1.should == {}
  end.and_return(true)

但是,没有 block 的彩色 diff 输出仍然很有用。

最佳答案

我相信 Rspec 默认会为您提供更好的数组差异输出。我不记得确切的语法,但例如,类似

expected: [a, b, c]
got:      [a, d]
diff: - [b]
        [c]
      + [d]

根据您的具体情况,您可以将散列转换为数组以使用它。

myHash.map{ |key, value| value}

myHash.values

关于ruby - RSpec should_receive( :send). with(...): colored diff,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30859743/

相关文章:

javascript - 如何在 JavaScript 中访问实例变量?

ruby-on-rails - Windows 8.1 上的 Ruby、Rails 开发环境

python - Nose 测试和类方法

python - 在 Django 测试框架中使用 Basic HTTP 访问认证

php - 等同于 PHP 的 .= 运算符的 ruby​​?

ruby - 升级 jruby 和 ruby​​mine 版本后无法安装 bundler/gems (SSLError)

unit-testing - 测试 nServicebus 中的消息 header

php - 如何使用 phpunit_selenium2 扩展执行双击?

testing - 如何在 wfetch 中指定 POST 参数

php - Symfony 功能测试 JSON