ruby – RSpec自定义diffable匹配器

前端之家收集整理的这篇文章主要介绍了ruby – RSpec自定义diffable匹配器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在RSpec中有一个自定义匹配器,忽略空格/换行符,只匹配内容
RSpec::Matchers.define :be_matching_content do |expected|
  match do |actual|
    actual.gsub(/\s/,'').should == expected.gsub(/\s/,'')
  end

  diffable
end

我可以像这样使用它:

body = "   some data   \n more data"
    body.should be_matching_content("some data\nmore wrong data")

但是,当测试失败时(如上所述),diff输出看起来不太好:

-some data
   -more wrong data
   +   some data   
   + more data

是否可以配置diffable输出?第一行有些数据是正确的,但第二行错误数据是错误的.仅将第二行作为失败的根本原因是非常有用的.

解决方法

我相信你应该在RSpec中禁用默认的diffable行为并替换你自己的实现:
RSpec::Matchers.define :be_matching_content do |expected|
  match do |actual|
    @stripped_actual = actual.gsub(/\s/,'')
    @stripped_expected = expected.gsub(/\s/,'')
    expect(@stripped_actual).to eq @stripped_expected
  end

  failure_message do |actual|
    message = "expected that #{@stripped_actual} would match #{@stripped_expected}"
    message += "\nDiff:" + differ.diff_as_string(@stripped_actual,@stripped_expected)
    message
  end

  def differ
    RSpec::Support::Differ.new(
        :object_preparer => lambda { |object| RSpec::Matchers::Composable.surface_descriptions_in(object) },:color => RSpec::Matchers.configuration.color?
    )
  end
end

RSpec.describe 'something'do
  it 'should diff correctly' do
    body = "   some data   \n more data"
    expect(body).to be_matching_content("some data\nmore wrong data")
  end
end

产生以下内容

Failures:

  1) something should diff correctly
     Failure/Error: expect(body).to be_matching_content("some data\nmore wrong data")
       expected that somedatamoredata would match somedatamorewrongdata
       Diff:
       @@ -1,2 +1,2 @@
       -somedatamorewrongdata
       +somedatamoredata

如果需要,您可以使用自定义不同,甚至可以将整个匹配器重新实现为对diff命令的系统调用,如下所示:

♥ diff -uw --label expected --label actual <(echo "   some data    \n more data") <(echo "some data\nmore wrong data")
--- expected
+++ actual
@@ -1,2 @@
    some data    
- more data
+more wrong data

干杯!

原文链接:https://www.f2er.com/ruby/268703.html

猜你在找的Ruby相关文章