45

在 RSpec 中:我可以像在 xUnit 样式测试框架中那样将消息附加到检查吗?如何?

assert_equal value1, value2, 'something is wrong'
4

3 回答 3

61

对于 RSpec 3+:

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

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

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

来源@relishapp


对于较旧的 RSpec 版本

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

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

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

于 2010-11-15T11:40:38.290 回答
28

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

这是RSpec 文档中的一个示例:

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_shouldandmatch_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
于 2010-11-15T11:21:17.990 回答
6

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

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

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

        expect(coder.is_partial?(v)).to eq(p), "expected #{v} for #{p}"
于 2015-07-03T14:31:00.350 回答