How to write a diffable matcher with Rspec2

為{幸葍}努か 提交于 2019-12-11 03:42:46

问题


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

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 ?

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).


回答1:


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

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




回答2:


Use failure_message_for_should block :-

failure_message_for_should do |actual|
  "expected: #{expected} \n     got: #{actual}"
end

Then .to_hash what you need to see.



来源:https://stackoverflow.com/questions/12551564/how-to-write-a-diffable-matcher-with-rspec2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!