RSpec - 存根



如果您已閱讀 RSpec Doubles(又稱 Mocks)部分,那麼您就已瞭解 RSpec Stubs。在 RSpec 中,一個存根通常稱為方法存根,這是一種特殊的方法型別,可“替代”現有方法或尚未存在的方法。

以下是 RSpec Doubles 部分中的程式碼 −

class ClassRoom 
   def initialize(students) 
      @students = students 
   End
   
   def list_student_names 
      @students.map(&:name).join(',') 
   end 
end 

describe ClassRoom do 
   it 'the list_student_names method should work correctly' do 
      student1 = double('student') 
      student2 = double('student') 
      
      allow(student1).to receive(:name) { 'John Smith'}
      allow(student2).to receive(:name) { 'Jill Smith'} 
      
      cr = ClassRoom.new [student1,student2]
      expect(cr.list_student_names).to eq('John Smith,Jill Smith') 
   end 
end

在我們的示例中,allow() 方法提供了我們需要用於測試 ClassRoom 類的存根方法。在這種情況下,我們需要能夠像 Student 類的例項一樣執行的物件,但此類實際上不存在(目前)。我們知道 Student 類需要提供一個 name() 方法,並使用 allow() 為 name () 建立一個存根方法。

需要注意的一點是,RSpec 的語法多年來已稍有變化。在早期版本的 RSpec 中,上述存根方法的定義如下 −

student1.stub(:name).and_return('John Smith') 
student2.stub(:name).and_return('Jill Smith')

讓我們採用上述程式碼並使用舊的 RSpec 語法替換這兩行 allow()

class ClassRoom 
   def initialize(students) 
      @students = students 
   end 
   
   def list_student_names 
      @students.map(&:name).join(',') 
   end 
	
end 

describe ClassRoom do 
   it 'the list_student_names method should work correctly' do 
      student1 = double('student') 
      student2 = double('student')
      
      student1.stub(:name).and_return('John Smith')
      student2.stub(:name).and_return('Jill Smith') 
      
      cr = ClassRoom.new [student1,student2] 
      expect(cr.list_student_names).to eq('John Smith,Jill Smith') 
   end 
end

當您執行上述程式碼時,會看到此輸出 −

.
Deprecation Warnings:

Using `stub` from rspec-mocks' old `:should` syntax without explicitly 
   enabling the syntax is deprec 

ated. Use the new `:expect` syntax or explicitly enable `:should` instead. 
   Called from C:/rspec_tuto 

rial/spec/double_spec.rb:15: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.002 seconds (files took 0.11401 seconds to load)
1 example, 0 failures

建議您在 RSpec 示例中需要建立存根方法時,使用新的 allow() 語法,但我們在此處提供了較舊的樣式,以便您在看到時能夠識別它。

廣告
© . All rights reserved.