【问题标题】:RSpec should_receive(:send).with(...): colored diffRSpec should_receive(:send).with(...): 彩色差异
【发布时间】:2015-06-16 05:52:33
【问题描述】:

我正在大量使用 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 启用了彩色输出,但这只是将失败的测试涂成红色。

有没有办法获得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)

但是,没有块的彩色差异输出仍然很有用。

【问题讨论】:

    标签: ruby unit-testing testing rspec


    【解决方案1】:

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

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

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

    myHash.map{ |key, value| value}
    

    myHash.values
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-02
      • 2014-02-11
      • 1970-01-01
      • 1970-01-01
      • 2012-09-16
      • 2014-05-12
      • 1970-01-01
      • 2017-07-15
      相关资源
      最近更新 更多