How to attach message to rspec check?

后端 未结 3 2031
野的像风
野的像风 2021-02-01 13:41

In rspec: Can I attach a message to a check the same way as I would do in xUnit style test frameworks? How?

assert_equal value1, value2, \"something is wrong\"
<         


        
3条回答
  •  余生分开走
    2021-02-01 13:52

    In RSpec, it's the matcher's job to print a sensible failure message. The generic matchers that ship with RSpec can obviously only print generic non-descript failure messages, since they don't know anything about your particular domain. That's why it is recommended that you write your own domain-specific matchers, which will give you both more readable tests and more readable failure messages.

    Here's an example from the RSpec documentation:

    require 'rspec/expectations'
    
    RSpec::Matchers.define :be_a_multiple_of do |expected|
      match do |actual|
        (actual % expected).zero?
      end
      failure_message_for_should do |actual|
        "expected that #{actual} would be a multiple of #{expected}"
      end
      failure_message_for_should_not do |actual|
        "expected that #{actual} would not be a multiple of #{expected}"
      end
      description do
        "be multiple of #{expected}"
      end
    end
    

    Note: only match is required, the others will be generated automatically. However, the whole point of your question is of course that you do not like the default messages, so you need to at least also define failure_message_for_should.

    Also, you can define match_for_should and match_for_should_not instead of match if you need different logic in the positive and negative case.

    As @Chris Johnsen shows, you can also explicitly pass a message to the expectation. However, you run the risk of losing the readability advantages.

    Compare this:

    user.permissions.should be(42), 'user does not have administrative rights'
    

    with this:

    user.should have_administrative_rights
    

    That would (roughly) be implemented like this:

    require 'rspec/expectations'
    
    RSpec::Matchers.define :have_administrative_rights do
      match do |thing|
        thing.permissions == 42
      end
      failure_message_for_should do |actual|
        'user does not have administrative rights'
      end
      failure_message_for_should_not do |actual|
        'user has administrative rights'
      end
    end
    

提交回复
热议问题