当你学习RSpec时,你可能会阅读很多关于期望的内容,起初可能有点令人困惑.当你看到术语期望和减去时,你应该记住两个主要细节;
期望只是一个陈述在 it block 中使用 expect()方法.而已.它并不复杂.如果您有这样的代码: expect(1 + 1).to eq(2),您的示例中有一个Expectation.您期望表达式 1 + 1 评估为 2 .由于RSpec是BDD测试框架,因此措辞很重要.通过将此语句称为Expectation,很明显您的RSpec代码正在描述它正在测试的代码的"行为".我们的想法是,您正在以类似文档的方式表达代码的行为方式.
Expectation语法相对较新.在引入 expect()方法之前(早在2012年),RSpec使用了基于 should()方法的不同语法.上述期望用旧语法写成:(1 + 1).should eq(2).
使用较旧的基于代码或较旧版本的RSpec时,您可能会遇到Expectations的旧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().