定义可比较匹配器

当匹配器被定义为可比较时,输出将包括提交对象的差异,当对象比简单的基元更复杂时。

定义可比较匹配器 (使用 diff-lcs 1.4)

给定一个名为 “diffablematcherspec.rb” 的文件,其中包含

RSpec::Matchers.define :be_just_like do |expected|
  match do |actual|
    actual == expected
  end

  diffable
end

RSpec.describe "two\nlines" do
  it { is_expected.to be_just_like("three\nlines") }
end

我运行 rspec ./diffable_matcher_spec.rb

那么它应该失败,并显示

       Diff:
       @@ -1 +1 @@
       -three
       +two

定义可比较匹配器 (使用 diff-lcs 1.3)

给定一个名为 “diffablematcherspec.rb” 的文件,其中包含

RSpec::Matchers.define :be_just_like do |expected|
  match do |actual|
    actual == expected
  end

  diffable
end

RSpec.describe "two\nlines" do
  it { is_expected.to be_just_like("three\nlines") }
end

我运行 rspec ./diffable_matcher_spec.rb

那么它应该失败,并显示

       Diff:
       @@ -1,3 +1,3 @@
       -three
       +two
        lines

重新定义 actual (使用 diff-lcs 1.4.4)

有时需要覆盖 actual 以使比较工作,例如,如果 actual 是你想要从中读取的文件的名称。为了使这起作用,你需要在你的匹配器中覆盖 @actual

给定一个名为 “redefineactualmatcher_spec.rb” 的文件,其中包含

RSpec::Matchers.define :have_content do |expected|
  match do |actual|
    @actual = File.read(actual).chomp

    values_match? expected, @actual
  end

  diffable
end

RSpec.describe 'Compare files' do
  context 'when content is equal' do
    it { expect('data.txt').to have_content 'Data' }
  end

  context 'when files are different' do
    it { expect('data.txt').to have_content "No\nData\nhere" }
  end
end

以及一个名为 “data.txt” 的文件,其中包含

Data

我运行 rspec ./redefine_actual_matcher_spec.rb --format documentation

那么退出状态应该不为 0

以及输出应该包含

2 examples, 1 failure

以及输出应该包含

       @@ -1,4 +1,2 @@
       -No
        Data
       -here

重新定义 actual (使用 diff-lcs 1.3)

给定一个名为 “redefineactualmatcher_spec.rb” 的文件,其中包含

RSpec::Matchers.define :have_content do |expected|
  match do |actual|
    @actual = File.read(actual).chomp

    values_match? expected, @actual
  end

  diffable
end

RSpec.describe 'Compare files' do
  context 'when content is equal' do
    it { expect('data.txt').to have_content 'Data' }
  end

  context 'when files are different' do
    it { expect('data.txt').to have_content "No\nData\nhere" }
  end
end

以及一个名为 “data.txt” 的文件,其中包含

Data

我运行 rspec ./redefine_actual_matcher_spec.rb --format documentation

那么退出状态应该不为 0

以及输出应该包含

2 examples, 1 failure

以及输出应该包含

       @@ -1,4 +1,2 @@
       -No
        Data
       -here