- RSpec 教程
- RSpec——主頁
- RSpec——引言
- RSpec——基本語法
- RSpec——編寫規範
- RSpec——匹配器
- RSpec——測試替身
- RSpec——存根
- RSpec——鉤子
- RSpec——標記
- RSpec——物件
- RSpec——輔助方法
- RSpec——元資料
- RSpec——篩選
- RSpec——預期
- RSpec 資源
- RSpec——快速指南
- RSpec——有用資源
- RSpec——討論
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 塊取代該塊,最終所需的程式碼更少,並且一樣清晰。
廣告