rspec 中的自定义匹配器

Custom matchers in rspec

我正在 rspec 中编写我的第一个自定义匹配器。我想提供一条失败消息,详细说明比较失败的原因。实际上,我想输出预期对象和实际对象之间的差异。我实际上只需要对对象上的 2 个数组执行此操作。我做了一些研究,正在尝试按照 here 所述使用 =~。它提到它有一条信息丰富的失败消息,但我正在努力访问失败消息。我实际上只想 return 两个单独数组的组合失败消息,以便为匹配器 returning false 提供信息性原因。

我的尝试如下

    RSpec::Matchers.define :have_same_state_as_measure_table do |expected_measure_table , max_delta = 1e-06|

  match do |actual_measure_table|
   actual_measure_table.equivalence(expected_measure_table, max_delta)
  end

  description do
    "checks if measure has same state as expected measure table within a given number of precision"
  end

  # Optional method description
  description do
    "checks if measure has same state as expected measure table, within a given level of precision"
  end

  # Optional failure messages
  failure_message do |actual_measure_table|
    mismatch_string = ""
    mismatch_string += (actual_measure_table.columns =~ expected_measure_table.columns || "")
    mismatch_string += (actual_measure_table.names =~ expected_measure_table.names || "")
    "Measure tables missmatch as follows %s" % (mismatch_string.to_s)
  end

  failure_message_when_negated do |actual_measure_table|
    "expected friend not to be in zipcode"
  end

  end

我的最终匹配器如下:

class CompareMeasureTables

  attr_reader :expected_measure_table, :max_delta, :actual_measure_table

  def initialize(expected_measure_table, max_delta=1e-06)
    @expected_measure_table = expected_measure_table
    @max_delta = max_delta
  end

  def description
    "Checks if measure has same state as expected measure table, within a given level of precision"
  end

  def matches?(actual_measure_table)
    @actual_measure_table = actual_measure_table
    actual_measure_table.equivalence(expected_measure_table, max_delta, false)
  end

  def failure_message
    @mismatch_description = ""
    if actual_measure_table.columns.sort != expected_measure_table.columns.sort
      @mismatch_description += "\nColumns mismatch \nExpected =" + expected_measure_table.columns.inspect
      @mismatch_description += "\nActual =" + actual_measure_table.columns.inspect
    end

    if (@mismatch_description == "")
      @mismatch_description += "\nData mismatch \nExpected =" + (expected_measure_table.records - actual_measure_table.records).inspect
      @mismatch_description += "\nActual =" + (actual_measure_table.records - expected_measure_table.records).inspect
      @mismatch_description += "\nTolerance set at #{@max_delta}"
    end

    "Measure tables mismatch as follows %s" % (@mismatch_description)
  end

end