Chef - ChefSpec

Test Driven Development (TDD)è un modo per scrivere un test unitario prima di scrivere qualsiasi codice ricetta effettivo. Il test dovrebbe essere reale e dovrebbe convalidare ciò che fa una ricetta. In realtà dovrebbe fallire perché non è stata sviluppata alcuna ricetta. Una volta sviluppata la ricetta, il test dovrebbe passare.

ChefSpec si basa sul popolare framework RSpec e offre una sintassi su misura per testare la ricetta di Chef.

Creazione di ChefSpec

Step 1 - Crea un file gem contenente la gemma chefSpec.

[email protected]:~/chef-repo $ subl Gemfile 
source 'https://rubygems.org' 
gem 'chefspec'

Step 2 - Installa la gemma.

[email protected]:~/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!

Step 3 - Crea una directory specifica.

[email protected]:~/chef-repo $ mkdir cookbooks/<Cookbook Name>/spec

Step 4 - Crea una specifica

[email protected]:~/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

Step 5 - Convalida ChefSpec.

[email protected]:~/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

Step 6 - Modifica ricetta predefinita dei libri di cucina.

[email protected]:~/chef-repo $ subl cookbooks/<Cookbook Name>/recipes/default.rb 
template '/tmp/greeting.txt' do 
   variables greeting: 'Hello!' 
end

Step 7 - Crea un file modello.

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

Step 8 - Esegui di nuovo rspec.

[email protected]:~/chef-repo $ rspec cookbooks/<Cookbook Name>/spec/default_spec.rb 
. 
Finished in 0.10142 seconds 
1 example, 0 failures

Come funziona

Per farlo funzionare, dobbiamo prima configurare l'infrastruttura di base per l'utilizzo di RSpec con Chef. Quindi abbiamo bisogno di ChefSpec Ruby gem e il ricettario ha bisogno di una directory chiamata spec dove verranno salvati tutti i test.