Chef - ChefSpec



測試驅動開發 (TDD) 是一種在編寫任何實際的菜譜程式碼之前編寫單元測試的方法。測試應該是真實的,並且應該驗證菜譜的功能。由於尚未開發菜譜,因此測試應該首先失敗。一旦開發出菜譜,測試應該透過。

ChefSpec 基於流行的 RSpec 框架,並提供用於測試 Chef 菜譜的定製語法。

建立 ChefSpec

步驟 1 - 建立包含 chefSpec gem 的 gem 檔案。

vipin@laptop:~/chef-repo $ subl Gemfile 
source 'https://rubygems.org' 
gem 'chefspec' 

步驟 2 - 安裝 gem。

vipin@laptop:~/chef-repo $ bundler install 
Fetching gem metadata from https://rubygems.org/ 
...TRUNCATED OUTPUT... 
Installing chefspec (1.3.1) 
Using bundler (1.3.5) 
Your bundle is complete! 

步驟 3 - 建立 spec 目錄。

vipin@laptop:~/chef-repo $ mkdir cookbooks/<Cookbook Name>/spec 

步驟 4 - 建立 Spec

vipin@laptop:~/chef-repo $ subl  
cookbooks/my_cookbook/spec/default_spec.rb  
require 'chefspec'  
describe 'my_cookbook::default' do  
   let(:chef_run) {  
      ChefSpec::ChefRunner.new(  
         platform:'ubuntu', version:'12.04'  
      ).converge(described_recipe)  
   }  

   it 'creates a greetings file, containing the platform  
   name' do  
      expect(chef_run).to  
      create_file_with_content('/tmp/greeting.txt','Hello! ubuntu!')  
   end  
end 

步驟 5 - 驗證 ChefSpec。

vipin@laptop:~/chef-repo $ rspec cookbooks/<Cookbook Name>/spec/default_spec.rb 
F 
Failures: 
1) <CookBook Name> ::default creates a greetings file, containing the platform name 
Failure/Error: expect(chef_run.converge(described_recipe)).to 
create_file_with_content('/tmp/greeting.txt','Hello! ubuntu!') 
File content: 
does not match expected: 
Hello! ubuntu! 
# ./cookbooks/my_cookbook/spec/default_spec.rb:11:in `block 
(2 levels) in <top (required)>' 
Finished in 0.11152 seconds 
1 example, 1 failure  

Failed examples: 
rspec ./cookbooks/my_cookbook/spec/default_spec.rb:10 # my_ 
cookbook::default creates a greetings file, containing the 
platform name 

步驟 6 - 編輯 Cookbook 的預設菜譜。

vipin@laptop:~/chef-repo $ subl cookbooks/<Cookbook Name>/recipes/default.rb 
template '/tmp/greeting.txt' do 
   variables greeting: 'Hello!' 
end 

步驟 7 - 建立模板檔案。

vipin@laptop:~/chef-repo $ subl cookbooks/< Cookbook Name>/recipes/default.rb 
<%= @greeting %> <%= node['platform'] %>! 

步驟 8 - 再次執行 rspec。

vipin@laptop:~/chef-repo $ rspec cookbooks/<Cookbook Name>/spec/default_spec.rb 
. 
Finished in 0.10142 seconds 
1 example, 0 failures 

工作原理

為了使其正常工作,我們首先需要設定使用 RSpec 和 Chef 的基本基礎架構。然後,我們需要 ChefSpec Ruby gem,並且 Cookbook 需要一個名為 spec 的目錄來儲存所有測試。

廣告