首页 > 解决方案 > How to define a negated description for a custom matcher

问题描述

When i test stuff with rspec/ruby i use a lot of custom matchers. One of the big advandages for me it that i can create custom failure messages and descriptions. I use the descriptions to print out the expected behaviour at the bgeinning of the test. But i have a problem when a negate matchers.

I would like to define a description_when_negated. Is their a way to know if a matcher is negated in the description part? Or can i know it in the match part and print out somthing different.

Simple code example:

Spec::Matchers.define :have_value do |expected_value|
  match do |actual|
    puts "Expect: #{description}"

    actual.value == expected_value
  end

  description do
    "Object'#{actual.id}' should have value '#{expected_value}'"
  end

  failure_message do |actual|
    "Object'#{actual.id}' has value '#{actual.value}' instead of '#{expected_value}'"
  end

  failure_message_when_negated do |actual|
    "Object'#{actual.id}' has value '#{actual.value}' and that was not expected"
  end
end

Test:

expect(object1).to have_value(1235)
expect(object1).to have_name('test')
expect(object1).to_not have_description('test')

Output:

Expect Object 1 to have value '1235'  
Expect Object 1 to have name 'test'
Expect Object 1 to NOT have description 'test'

标签: rubyrspecmatcher

解决方案


推荐阅读