RSpec - 期望


当您学习 RSpec 时,您可能会阅读很多有关期望的内容,一开始可能会有点困惑。当您看到“期望”一词时,您应该记住两个主要细节 -

  • Expectation 只是it 块中使用expect()方法的语句。就是这样。没有比这更复杂的了。当您有这样的代码时:expect(1 + 1).to eq(2),您的示例中有一个 Expectation 。您期望表达式1 + 1的计算结果为2。不过,措辞很重要,因为 RSpec 是一个 BDD 测试框架。通过将此语句称为“期望”,很明显您的 RSpec 代码正在描述其正在测试的代码的“Behave”。这个想法是,您以类似于文档的方式表达代码的Behave方式。

  • Expectation 语法相对较新。在引入Expect()方法之前(早在 2012 年),RSpec 使用基于should()方法的不同语法。上面的 Expectation 在旧语法中是这样写的:(1 + 1).should eq(2)

在使用基于旧代码或旧版本的 RSpec 时,您可能会遇到期望的旧 RSpec 语法。如果您在新版本的 RSpec 中使用旧语法,您将看到一条警告。

例如,使用以下代码 -

RSpec.describe "An RSpec file that uses the old syntax" do
   it 'you should see a warning when you run this Example' do 
      (1 + 1).should eq(2) 
   end 
end

当你运行它时,你将得到如下所示的输出 -

. Deprecation Warnings:

Using `should` from rspec-expectations' old `:should` 
   syntax without explicitly enabling the syntax is deprecated. 
   Use the new `:expect` syntax or explicitly enable 
	
`:should` with `config.expect_with( :rspec) { |c| c.syntax = :should }`
   instead. Called from C:/rspec_tutorial/spec/old_expectation.rb:3 :in 
   `block (2 levels) in <top (required)>'.

If you need more of the backtrace for any of these deprecations to
   identify where to make the necessary changes, you can configure 
`config.raise_errors_for_deprecations!`, and it will turn the deprecation 
   warnings into errors, giving you the full backtrace.

1 deprecation warning total 
Finished in 0.001 seconds (files took 0.11201 seconds to load) 
1 example, 0 failures

除非您需要使用旧语法,否则强烈建议您使用expect() 而不是should()。