RSpec——物件



RSpec 的一項優勢在於它提供了多種編寫測試的方法,編寫清晰的測試。當測試簡短且有條理時,就不必關注測試如何編寫的細節,而可以輕鬆專注於預期行為。RSpec 物件是另一種捷徑,可讓你編寫簡單明瞭的測試。

考慮此程式碼 −

class Person 
   attr_reader :first_name, :last_name 
   
   def initialize(first_name, last_name) 
      @first_name = first_name 
      @last_name = last_name 
   end 
end 

describe Person do 
   it 'create a new person with a first and last name' do
      person = Person.new 'John', 'Smith'
      
      expect(person).to have_attributes(first_name: 'John') 
      expect(person).to have_attributes(last_name: 'Smith') 
   end 
end

它實際上相當清晰,但我們可以使用 RSpec 的 subject 特性來減少示例中的程式碼量。為此,我們將 person 物件例項化移至 describe 行中。

class Person 
   attr_reader :first_name, :last_name 
   
   def initialize(first_name, last_name) 
      @first_name = first_name 
      @last_name = last_name 
   end 
	
end 

describe Person.new 'John', 'Smith' do 
   it { is_expected.to have_attributes(first_name: 'John') } 
   it { is_expected.to have_attributes(last_name: 'Smith') }
end

執行此程式碼時,你會看到以下輸出 −

.. 
Finished in 0.003 seconds (files took 0.11201 seconds to load) 
2 examples, 0 failures

請注意,第二個程式碼示例要簡單得多。我們獲取第一個示例中的一個it 塊,並用兩個it 塊取代該塊,最終所需的程式碼更少,並且一樣清晰。

廣告
© . All rights reserved.