かべぎわブログ

ブログです

Serverspecをつかってみる

概要

Serverspecをさわってみます。

Serverspecのインストール

Rubyがはいっていればこれだけでインストールができます。

$ gem install serverspec

Serverspecの設定

以下コマンドを入力してServerspecの設定を行います。
OSはUNIXで対象はExec(local)にしています。

$ serverspec-init

serverspec-init
Select OS type:

  1) UN*X
  2) Windows

Select number: 1

Select a backend type:

  1) SSH
  2) Exec (local)

Select number: 2

するとこんなかんじのファイル群ができます。

$ tree ./spec
./spec
├── localhost
│   └── sample_spec.rb
└── spec_helper.rb

テストしてみる

./spec/localhost/sample_spec.rbがlocalhost環境で実行されるテストファイルになるのでこれをかんたんに以下のように書き換えてみる。
cronが起動しているかどうかテストするようにしている。

require 'spec_helper'

describe service('cron') do
    it { should be_running }
end

rake specコマンドを実行するとこのテストが実行される。
0 failuresとなっていることがわかる。

rake spec
/usr/bin/ruby2.5 -I/var/lib/gems/2.5.0/gems/rspec-support-3.8.0/lib:/var/lib/gems/2.5.0/gems/rspec-core-3.8.0/lib /var/lib/gems/2.5.0/gems/rspec-core-3.8.0/exe/rspec --pattern spec/localhost/\*_spec.rb
/var/lib/gems/2.5.0/gems/rspec-core-3.8.0/lib/rspec/core/rake_task.rb:79: warning: Insecure world writable dir /root/.rbenv/shims in PATH, mode 040777

Service "cron"
/var/lib/gems/2.5.0/gems/specinfra-2.76.7/lib/specinfra/backend/exec.rb:123: warning: Insecure world writable dir /root/.rbenv/shims in PATH, mode 040777
  should be running

Finished in 0.72735 seconds (files took 1.24 seconds to load)
1 example, 0 failures

当然cronはうごいている。

$ service cron status
 * cron is running

cronを止めてからテストしてみると

$ service cron stop
$ service cron status
 * cron is not running

1 failureとなっていることがわかる。

rake spec
/usr/bin/ruby2.5 -I/var/lib/gems/2.5.0/gems/rspec-support-3.8.0/lib:/var/lib/gems/2.5.0/gems/rspec-core-3.8.0/lib /var/lib/gems/2.5.0/gems/rspec-core-3.8.0/exe/rspec --pattern spec/localhost/\*_spec.rb
/var/lib/gems/2.5.0/gems/rspec-core-3.8.0/lib/rspec/core/rake_task.rb:79: warning: Insecure world writable dir /root/.rbenv/shims in PATH, mode 040777

Service "cron"
/var/lib/gems/2.5.0/gems/specinfra-2.76.7/lib/specinfra/backend/exec.rb:123: warning: Insecure world writable dir /root/.rbenv/shims in PATH, mode 040777
  should be running (FAILED - 1)

Failures:

  1) Service "cron" should be running
     On host `localhost'
     Failure/Error: it { should be_running }
       expected Service "cron" to be running
       /bin/sh -c ps\ aux\ \|\ grep\ -w\ --\ cron\ \|\ grep\ -qv\ grep

     # ./spec/localhost/sample_spec.rb:5:in `block (2 levels) in <top (required)>'

Finished in 0.83032 seconds (files took 1.26 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./spec/localhost/sample_spec.rb:5 # Service "cron" should be running

/usr/bin/ruby2.5 -I/var/lib/gems/2.5.0/gems/rspec-support-3.8.0/lib:/var/lib/gems/2.5.0/gems/rspec-core-3.8.0/lib /var/lib/gems/2.5.0/gems/rspec-core-3.8.0/exe/rspec --pattern spec/localhost/\*_spec.rb failed

おわりに

やってみた。

Serverspec

Serverspec