模块: RSpec::Expectations

定义于
lib/rspec/expectations.rb,
lib/rspec/expectations/syntax.rb,
lib/rspec/expectations/handler.rb,
lib/rspec/expectations/version.rb,
lib/rspec/expectations/fail_with.rb,
lib/rspec/expectations/configuration.rb,
lib/rspec/expectations/expectation_target.rb,
lib/rspec/expectations/failure_aggregator.rb,
lib/rspec/expectations/minitest_integration.rb,
lib/rspec/expectations/block_snippet_extractor.rb

概述

RSpec::Expectations 提供了一个简单易读的 API,用于表达代码示例中预期的结果。要表达预期的结果,请将对象或块包装在 expect 中,调用 toto_not(别名为 not_to),并将匹配器对象传递给它

expect(order.total).to eq(Money.new(5.55, :USD))
expect(list).to include(user)
expect(message).not_to match(/foo/)
expect { do_something }.to raise_error

最后一种形式(块形式)是用来匹配不是对象,而只能在执行代码块时观察到的 Ruby 结构。这包括引发错误、抛出符号、生成和更改值。

expect(...).to 与匹配器一起调用时,它会反过来调用 matcher.matches?(<被 expect 包装的对象>)。例如,在表达式中

expect(order.total).to eq(Money.new(5.55, :USD))

...eq(Money.new(5.55, :USD)) 返回一个匹配器对象,它相当于 eq.matches?(order.total)。如果 matches? 返回 true,则预期结果得到满足,执行继续。如果返回 false,则规范将失败,并显示 eq.failure_message 返回的消息。

鉴于表达式

expect(order.entries).not_to include(entry)

...not_to 方法(也可用作 to_not)调用相当于 include.matches?(order.entries) 的内容,但它将 false 解释为成功,将 true 解释为失败,并使用由 include.failure_message_when_negated 生成的消息。

rspec-expectations 附带了一套标准的有用匹配器,编写自己的匹配器非常简单。

有关 rspec-expectations 附带的内置匹配器以及如何编写自己的自定义匹配器的更多信息,请参阅 RSpec::Matchers

定义在命名空间下

模块: Syntax 类: Configuration, ExpectationNotMetError, ExpectationTarget, MultipleExpectationsNotMetError

类方法摘要 收起

类方法详情

.configurationRSpec::Expectations::Configuration

配置对象。

返回

223
224
225
# File 'lib/rspec/expectations/configuration.rb', line 223
def self.configuration
  @configuration ||= Configuration.new
end

.fail_with(message, expected = nil, actual = nil) ⇒Object

使用 message 抛出 RSpec::Expectations::ExpectationNotMetError。当 expectedactual 都存在时,在失败消息中添加一个 diff。

参数

  • message (String)
  • expected (Object) (默认值为: nil)
  • actual (Object) (默认值为: nil)
27
28
29
30
31
32
33
34
35
36
# File 'lib/rspec/expectations/fail_with.rb', line 27
def fail_with(message, expected=nil, actual=nil)
  unless message
    raise ArgumentError, "Failure message is nil. Does your matcher define the " \
                         "appropriate failure_message[_when_negated] method to return a string?"
  end
  message = ::RSpec::Matchers::MultiMatcherDiff.from(expected, actual).message_with_diff(message, differ)
  RSpec::Support.notify_failure(RSpec::Expectations::ExpectationNotMetError.new message)
end