【问题标题】:How to attach a message to RSpec check?如何将消息附加到 RSpec 检查?
【发布时间】:2010-11-15 11:02:06
【问题描述】:

在 RSpec 中:我可以像在 xUnit 风格的测试框架中那样将消息附加到检查吗?怎么样?

assert_equal value1, value2, 'something is wrong'

【问题讨论】:

    标签: ruby tdd rspec xunit


    【解决方案1】:

    对于 RSpec 3+:

    消息可以自定义为字符串或使用过程(检查参考)。

    expect(1).to eq(2), 'one is not two!'
    

    自定义消息 RSpec 尝试提供有用的失败消息,但对于您想要更多的情况 具体信息,您可以在示例中定义自己的消息权。这适用于 除运算符匹配器之外的任何匹配器。

    source @ relishapp


    对于旧的 RSpec 版本

    shouldshould_not 采用第二个参数 (message),它会覆盖匹配器的默认消息。

    1.should be(2), 'one is not two!'
    

    不过,默认消息通常非常有用。

    【讨论】:

    • 如何使用#should ==
    • @mohawkjohn:它似乎类似于1.should(nil, 'one is not two!') == 2 (ick),但这确实有效,因为== 运算符匹配器看起来总是生成自己的消息。
    • 您也可以使用eq 代替==1.should eq(nil), 'one is not two!'
    【解决方案2】:

    在 RSpec 中,匹配器的工作是打印合理的失败消息。 RSpec 附带的通用匹配器显然只能打印通用的非描述性失败消息,因为它们对您的特定域一无所知。这就是为什么建议您编写自己的特定于域的匹配器,这将为您提供更易读的测试和更易读的失败消息。

    这是来自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
    

    注意:只需要match,其他的会自动生成。但是,您问题的全部意义当然是您喜欢默认消息,因此您至少还需要定义failure_message_for_should

    另外,如果您在正负情况下需要不同的逻辑,您可以定义match_for_shouldmatch_for_should_not 而不是match

    正如@Chris Johnsen 所示,您还可以明确地将消息传递给期望。但是,您可能会失去可读性优势。

    比较一下:

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

    用这个:

    user.should have_administrative_rights
    

    这将(大致)这样实现:

    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
    

    【讨论】:

    • 谢谢,我不知道定义匹配器的标准方法这么简单。虽然我更喜欢“懒惰”:当它们出现至少两次或显着简化使用它们的上下文时,将它们分解为单独的命名实体。
    【解决方案3】:

    就我而言,这是括号的问题:

            expect(coder.is_partial?(v)).to eq p, "expected #{v} for #{p}"
    

    这导致参数数量错误,而正确的方法是:

            expect(coder.is_partial?(v)).to eq(p), "expected #{v} for #{p}"
    

    【讨论】:

    • 我终于找到了这个解决方案。非常感谢。
    • 是的,对我来说就是这样。使用.to be(true) .
    猜你喜欢
    • 2019-12-14
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 2013-01-01
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多