gpt4 book ai didi

ruby - RSpec 自定义可区分匹配器

转载 作者:数据小太阳 更新时间:2023-10-29 06:48:27 25 4
gpt4 key购买 nike

我在 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

是否可以配置可微分输出?第一行some data是对的,但是第二行more wrong data是错的。仅将第二行作为失败的根本原因将非常有用。

最佳答案

我认为您应该禁用 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

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

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

干杯!

关于ruby - RSpec 自定义可区分匹配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32477104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com