忙しい人向けのserverspec入門 ~HelloWorld編(解説)~
目的
前回と同じ。serverspecを使ってみたいけど、導入が大変そうで抵抗を感じている人に、 serverspecの便利さを体験してもらう。
とりあえず
前回、hello worldしただけで、解説がまだだったので、解説する。
やってること
HelloWorld 編で作ったserverspecは下記の流れでテストを実行する。
Rakefile を読み込んで、rakeタスクを実行する
rakeタスクは spec/ディレクトリの配下の
*_spec.rb
という名前のファイルを探索して実行する。(ここでは、192.168.56.201/sample_spec.rb
が該当する) を実行するsample_spec.rb 内でrequireされた
spec_helper.rb
が必要なライブラリのインポート 、その他必要な準備(SSH接続とか)を行うsample_spec.rb 内で記述された rspec形式のテストを実行する
(どれも重要なのだけど)重要なのは4の、sample_spec.rb に記述されたrspec形式のテスト。 serverspecのテストを書く時間の8割はこのsample_spec.rb のようなrspec形式のテストを書く時間である。
sample_spec.rbのテストを書いてみると、こんな感じ
require 'spec_helper' describe package('httpd'), :if => os[:family] == 'redhat' do it { should be_installed } end describe package('apache2'), :if => os[:family] == 'ubuntu' do it { should be_installed } end describe service('httpd'), :if => os[:family] == 'redhat' do it { should be_enabled } it { should be_running } end describe service('apache2'), :if => os[:family] == 'ubuntu' do it { should be_enabled } it { should be_running } end describe service('org.apache.httpd'), :if => os[:family] == 'darwin' do it { should be_enabled } it { should be_running } end describe port(80) do it { should be_listening } end
describe
と記述されたブロックが全部で7つあるが、このうち、テストとして実行されるのは、
1,3,7 番目のブロックのみ。他は、os[:family] == 〇〇
の記述によりスキップされる。
※このスキップの機能は、ディストリビューションが混在しているようなクラスタ環境で テストをするときや、複数のディストリビューションに対応したansibleのroleなどのテストを する際に効果を発揮する。