Chef - ChefSpec



测试驱动开发 (TDD) 是一种在编写任何实际的菜谱代码之前编写单元测试的方法。测试应该是真实的,并且应该验证菜谱的功能。由于尚未开发菜谱,因此测试应该首先失败。一旦开发出菜谱,测试应该通过。

ChefSpec 基于流行的 RSpec 框架,并提供用于测试 Chef 菜谱的定制语法。

创建 ChefSpec

步骤 1 - 创建包含 chefSpec gem 的 gem 文件。

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

步骤 2 - 安装 gem。

vipin@laptop:~/chef-repo $ bundler install 
Fetching gem metadata from https://rubygems.org.cn/ 
...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 的目录来保存所有测试。

广告
© . All rights reserved.