如何使用 Rspec2 编写可区分的匹配器 [英] How to write a diffable matcher with Rspec2

查看:38
本文介绍了如何使用 Rspec2 编写可区分的匹配器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个匹配器,在与预期值进行比较之前将对象转换为哈希(假设我想比较 2 个哈希而不关心键是字符串或符号这一事实).

I'm trying to write a matcher which transforms object to a Hash before comparing to the expected value (let say that I want to compare 2 hashes without caring about the fact that keys are strings or symbols).

我可以很容易地定义一个匹配器

I can easily define a matcher doing this

RSpec::Matchers.define :my_matcher do |content|
    match { |to_match| my_hash_conversion(to_match) == my_hash_conversion(content)
    diffable
end

我添加了 diffable 以便 rspec 在两个对象不匹配时显示它们的差异.但是我想显示转换对象的差异而不是原始对象的差异?

I add diffable so rspec displays the diff of the two objects when they don't match. However I want to display the diff of the converted objects not the the diff of the original object ?

我看到它们在 Rspec 的某个地方有一个 Differ 类和一个 diff_with_hash 函数,但我不知道如何使用它(因为它没有真正记录).

I saw they are somewhere in Rspec a Differ class and a diff_with_hash function, but I have no idea how to use it (as it's not really documented).

推荐答案

对于 RSpec3,可以直接使用 Diff 类.

For RSpec3, you can use the Diff class directly.

RSpec::Matchers.define :my_matcher do |expected|
  expected_hash = my_hash_conversion(expected)
  match do |actual|
    actual_hash = my_hash_conversion(actual)
    expected_hash == actual_hash
  end

  failure_message do |actual|
    actual_hash = my_hash_conversion(actual)
    "expect #{expected_hash} to match #{actual_hash}" + 
      RSpec::Support::Differ.new.diff(actual_hash, expected_hash)
  end
end

注意:RSpec::Support 说它不应该直接使用.

Note: RSpec::Support says it's not supposed to be used directly.

这篇关于如何使用 Rspec2 编写可区分的匹配器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆