Chef - ChefSpec
测试驱动开发 (TDD) 是一种在编写任何实际Kitchen(配方)代码之前编写单元测试的方法。测试应该是真实的,并且应该验证Kitchen(配方)的作用。它实际上应该失败,因为没有开发Kitchen(配方)。Kitchen(配方)开发完成后,测试应该通过。
ChefSpec 建立在流行的 RSpec 框架上,并提供用于测试 Chef Kitchen(配方)的定制语法。
创建 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 − 编辑 Cookbooks 默认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 的目录,所有测试都将保存在该目录中。