rspec中的自定义匹配器

时间:2015-03-23 11:57:43

标签: arrays rspec matcher

我在rspec中编写我的第一个自定义匹配器。我想提供一个失败消息,分析比较失败的原因。实际上我想输出预期对象和实际对象之间的差异。我实际上只需要在对象上使用2个数组。我做了一些研究,并尝试使用=〜所描述的here。它提到它有一个信息性的失败消息,但我正在努力访问失败消息。我实际上只想返回两个单独数组的组合失败消息,以便为匹配器返回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

1 个答案:

答案 0 :(得分:0)

我的最终匹配者如下:

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