Chef ChefSpec
测试驱动开发 (TDD) 是一种在编写任何实际配方代码之前编写单元测试的方法。测试应该是真实的,并且应该验证配方的作用。它实际上应该失败,因为没有开发配方。配方开发完成后,测试应该会通过。
ChefSpec 基于流行的 RSpec 框架构建,并为测试 Chef recipe 提供了量身定制的语法。
创建 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-创建规范目录。
vipin@laptop:~/chef-repo $ mkdir cookbooks/<Cookbook Name>/spec
步骤 4-创建规范
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 并且说明书需要一个名为 spec 的目录,所有测试都将在其中保存。