Linux環境でServerspecを使ってみる part4

今回はこちらの続きで、Serverspecでテストを実行してみます。
前回:Linux環境でServerspecを使ってみる part3 - ressyのナレッジ的なブログ

サンプルのテストコード

前回、Serverspecの初期設定を実施したことで、以下のようなファイルが出来上がっているかと思います。

spec/WEB01/sample_spec.rb

これが、WEB01用のテストケースを記述したサンプルファイルになります。
内容はこのような感じになっていると思います。

$ cat spec/WEB01/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

大まかに説明すると、describeendまでで一括りとなっており、上から順に

  • OSがRedHat系の場合:httpdがインストールされているか
  • OSがUbuntu系の場合:apache2がインストールされているか
  • OSがRedHat系の場合:httpdが起動しているか
  • OSがUbuntu系の場合:apache2が起動しているか
  • OSがDarwinの場合:httpdが起動しているか
  • 80番ポートがリスニングしているか

がそれぞれ記述されています。
テスト対象のOSに応じて、適切にテストを実施できるように記載されています。

サンプルを使ってテストを実行

せっかくなので、このテストコードをそのまま実行してみましょう。
本ブログの勉強環境はCentOSを使用しているので、os[:family] == 'redhat'のテストが実行されます。
以下のように、Rakefileが置かれたディレクトリへ移動して、テストコマンドを実行します。

$ cd cd <任意のディレクトリ>/Serverspec
$ ASK_SUDO_PASSWORD=1 bundle exec rake
/usr/local/rbenv/versions/2.3.3/bin/ruby -I/usr/local/rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rspec-core-3.5.4/lib:/usr/local/rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rspec-support-3.5.0/lib /usr/local/rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/rspec-core-3.5.4/exe/rspec --pattern spec/WEB01/\*_spec.rb
Enter sudo password:

Package "httpd"
  should be installed

Service "httpd"
  should be enabled
  should be running

Port "80"
  should be listening

Finished in 0.45621 seconds (files took 3.99 seconds to load)
4 examples, 0 failures

テストが実行されいてる様子が、なんとなくでもわかるかと思います。
ちなみに、4 examples, 0 failuresと出ているので、「4件のテストを実施し、NGは0件でした」となります。
4件と言うのはshould be ....となっている部分(=実際のテスト部分)の件数になります。

以上で、サンプルのテストコードが実行できたことを確認できました。
次回は、実行したコマンドの解説をしたいと思います。

参考

この記事は、以下を参考にしています。

Serverspec - Home

「Serverspec」を使ってサーバー環境を自動テストしよう - さくらのナレッジ

Serverspecでサーバの構成をテストする 導入と個人的知見 - Qiita