- RSpec 教程
- RSpec - 首頁
- RSpec - 簡介
- RSpec - 基本語法
- RSpec - 編寫規範
- RSpec - 匹配器
- RSpec - 測試替身
- RSpec - 存根
- RSpec - 鉤子
- RSpec - 標籤
- RSpec - 主題
- RSpec - 輔助方法
- RSpec - 元資料
- RSpec - 過濾
- RSpec - 期望
- RSpec 資源
- RSpec - 快速指南
- RSpec - 有用資源
- RSpec - 討論
RSpec - 鉤子
編寫單元測試時,在測試前後執行設定和拆卸程式碼通常很方便。設定程式碼是配置或“設定”測試條件的程式碼。拆卸程式碼則進行清理,確保環境對於後續測試處於一致狀態。
一般來說,您的測試應該彼此獨立。當您執行整個測試套件並且其中一個測試失敗時,您希望確信它失敗是因為正在測試的程式碼存在錯誤,而不是因為之前的測試使環境處於不一致狀態。
RSpec中最常用的鉤子是`before`和`after`鉤子。它們提供了一種定義和執行我們上面討論的設定和拆卸程式碼的方法。讓我們考慮這個示例程式碼:
class SimpleClass
attr_accessor :message
def initialize()
puts "\nCreating a new instance of the SimpleClass class"
@message = 'howdy'
end
def update_message(new_message)
@message = new_message
end
end
describe SimpleClass do
before(:each) do
@simple_class = SimpleClass.new
end
it 'should have an initial message' do
expect(@simple_class).to_not be_nil
@simple_class.message = 'Something else. . .'
end
it 'should be able to change its message' do
@simple_class.update_message('a new message')
expect(@simple_class.message).to_not be 'howdy'
end
end
執行此程式碼後,您將獲得以下輸出:
Creating a new instance of the SimpleClass class . Creating a new instance of the SimpleClass class . Finished in 0.003 seconds (files took 0.11401 seconds to load) 2 examples, 0 failures
讓我們仔細看看發生了什麼。`before(:each)`方法是我們定義設定程式碼的地方。當您傳遞`:each`引數時,您正在指示`before`方法在示例組中的每個示例之前執行,即上面程式碼中`describe`塊內的兩個`it`塊。
在`@simple_class = SimpleClass.new`這一行中,我們正在建立`SimpleClass`類的新例項並將其賦值給物件的例項變數。您可能會好奇是什麼物件?RSpec在`describe`塊的範圍內幕後建立了一個特殊的類。這允許您將值賦值給此類的例項變數,您可以在示例中的`it`塊內訪問這些變數。這也使得在測試中編寫更簡潔的程式碼變得更容易。如果每個測試(示例)都需要`SimpleClass`的例項,我們可以將該程式碼放在`before`鉤子中,而無需將其新增到每個示例中。
請注意,“建立SimpleClass類的新例項”這一行被寫入控制檯兩次,這表明`before`鉤子在每個`it`塊中都被呼叫。
正如我們提到的,RSpec還有一個`after`鉤子,`before`和`after`鉤子都可以接受`all`作為引數。`after`鉤子將在指定的 target 後執行。`:all` target 意味著鉤子將在所有示例之前/之後執行。這是一個簡單的示例,說明每個鉤子何時被呼叫。
describe "Before and after hooks" do
before(:each) do
puts "Runs before each Example"
end
after(:each) do
puts "Runs after each Example"
end
before(:all) do
puts "Runs before all Examples"
end
after(:all) do
puts "Runs after all Examples"
end
it 'is the first Example in this spec file' do
puts 'Running the first Example'
end
it 'is the second Example in this spec file' do
puts 'Running the second Example'
end
end
執行上述程式碼後,您將看到此輸出:
Runs before all Examples Runs before each Example Running the first Example Runs after each Example .Runs before each Example Running the second Example Runs after each Example .Runs after all Examples