【问题标题】:Enable diffing for RSpec array matcher为 RSpec 数组匹配器启用差异
【发布时间】:2017-10-04 13:42:17
【问题描述】:

RSpec 在比较多行字符串时提供“差异”样式的输出。比较数组时有没有办法做类似的事情(除了将数组转换为多行字符串)?

【问题讨论】:

  • match_array 是您要找的吗?如果不是,那么它缺少什么期望的行为?
  • @TomLord match_array 不考虑元素的顺序,即expect([1,2,3]).to match_array([3,2,1]) 通过。
  • 就我而言,顺序很重要。
  • 哦,抱歉,我以为这就是您想要的。但是,当标准 eq 匹配器失败时,您实际上只是在“更好”的错误消息之后?
  • 是的。就是这样。输出足够长,以至于当匹配器失败时很难找到差异。

标签: arrays ruby rspec diff matcher


【解决方案1】:

我可能弄错了,但我不认为这个功能是 RSpec 内置的。

不过,你可以implement a custom matcher with a custom error message:

RSpec::Matchers.define(:eq_array) do |expected|
  match { |actual| expected == actual }

  failure_message do |actual|
    <<~MESSAGE
      expected: #{expected}
      got:      #{actual}

      diff:     #{Diffy::Diff.new(expected.to_s, actual.to_s).to_s(:color)}
    MESSAGE
  end
end

# Usage:

expect([1, 2, 3]).to eq_array([1, 4, 3])

此演示使用diffy 库;你可以按照你认为合适的方式实现它。

【讨论】:

猜你喜欢
  • 2021-11-18
  • 1970-01-01
  • 2014-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-17
  • 1970-01-01
相关资源
最近更新 更多