シェフ-ChefSpec
Test Driven Development (TDD)実際のレシピコードを書く前にユニットテストを書く方法です。テストは実際のものであり、レシピの機能を検証する必要があります。レシピが開発されていなかったため、実際には失敗するはずです。レシピが作成されると、テストに合格するはずです。
ChefSpecは人気のあるRSpecフレームワークに基づいて構築されており、Chefレシピをテストするためのカスタマイズされた構文を提供します。
ChefSpecの作成
Step 1 − chefSpecgemを含むgemファイルを作成します。
vipin@laptop:~/chef-repo $ subl Gemfile
source 'https://rubygems.org'
gem 'chefspec'
Step 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!
Step 3 −スペックディレクトリを作成します。
vipin@laptop:~/chef-repo $ mkdir cookbooks/<Cookbook Name>/spec
Step 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
Step 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
Step 6 −クックブックのデフォルトレシピを編集します。
vipin@laptop:~/chef-repo $ subl cookbooks/<Cookbook Name>/recipes/default.rb
template '/tmp/greeting.txt' do
variables greeting: 'Hello!'
end
Step 7 −テンプレートファイルを作成します。
vipin@laptop:~/chef-repo $ subl cookbooks/< Cookbook Name>/recipes/default.rb
<%= @greeting %> <%= node['platform'] %>!
Step 8 −rspecを再度実行します。
vipin@laptop:~/chef-repo $ rspec cookbooks/<Cookbook Name>/spec/default_spec.rb
.
Finished in 0.10142 seconds
1 example, 0 failures
使い方
それを機能させるには、最初にChefでRSpecを使用するための基本インフラストラクチャをセットアップする必要があります。次に、ChefSpec Ruby gemを実行する必要があり、クックブックには、すべてのテストが保存されるspecというディレクトリが必要です。