RSpec - 預期



在你學習RSpec時,你可能會讀到很多關於預期的內容,一開始可能會有一些困惑。當你看到術語預期時,你應當牢記兩個要點 -

  • 預期只是一種包含在it塊中的宣告,使用expect()方法。就是這樣。一點也不復雜。當你擁有如下程式碼時:expect(1 + 1).to eq(2),你的示例中就會包含一個預期。你預期表示式1 + 1評估結果為2。但是措辭很重要,因為RSpec是一個BDD測試框架。透過將此語句稱為預期,可以清楚地看出你的RSpec程式碼正在描述它正在測試的程式碼的“行為”。其思想是你以一種類似文件的方式表達程式碼應該如何表現的行為。

  • 期望語法相對較新。在引入expect()方法之前 (2012年),RSpec使用了基於should()方法的不同語法。在舊語法中,上述預期寫成如下:(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()。

廣告
© . All rights reserved.