ruby – RSpec自定义diffable匹配器
发布时间:2020-12-17 04:23:14 所属栏目:百科 来源:网络整理
导读:我在RSpec中有一个自定义匹配器,忽略空格/换行符,只匹配内容: RSpec::Matchers.define :be_matching_content do |expected| match do |actual| actual.gsub(/s/,'').should == expected.gsub(/s/,'') end diffableend 我可以像这样使用它: body = " some
我在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 datanmore 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 datanmore wrong data") end end 产生以下内容: Failures: 1) something should diff correctly Failure/Error: expect(body).to be_matching_content("some datanmore 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 datanmore wrong data") --- expected +++ actual @@ -1,2 @@ some data - more data +more wrong data 干杯! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |