GeekBox

IT系エンジニアの雑記

【Serverspec】テスト内容が正しそうなのにfailureになる場合

スポンサーリンク

例としてリソースタイプserviceのbe_enabledで以下のようなテストを実行しようとした場合。

describe service('httpd') do
  it { should be_enabled }
end

書き方は合ってるっぽいが結果はfailureになってしまった。 適当に検索してみるとどうやら「spec_helper.rb」の一部コメントアウトを外すといけるらしい。

結論として、実行時のパスの中に /sbin がないために実行できていないっぽい。 だから「spec_helper」内「/sbin:/usr/local/sbin:$PATH」を有効化すれば実行できるようになっている。

以下調査

出力結果から実際に実行してるコマンドが分かるので見てみる。

On host `hoge`
Failure/Error: it { should be_enabled }
   expected Service "httpd" to be enabled
   sudo -p 'Password: ' /bin/sh -c chkconfig\ --list\ httpd\ \|\ grep\ 3:on

これを実際の対象サーバ上で実行してみると、普通にいけてそう。

$ chkconfig --list httpd | grep 3:on
httpd           0:off   1:off   2:on    3:on    4:on    5:on    6:off

以下箇所のコメントアウトを外す。

# Set PATH
set :path, '/sbin:/usr/local/sbin:$PATH'

再度実行すると確かに成功した。

Service "httpd"
  should be enabled
 
Finished in 1.45 seconds (files took 0.26145 seconds to load)
1 example, 0 failures

以下のようなテストを実行してパスに関してもう少し調べてみる。

describe command('echo $PATH') do
  its(:stdout) { should match /test/ }
end

 => 

1) Command "echo $PATH" stdout should match /bian/
     On host `hoge'
     Failure/Error: its(:stdout) { should match /bian/ }
       expected "/usr/local/bin:/bin:/usr/bin\n" to match /bian/
       Diff:
       @@ -1,2 +1,2 @@
       -/bian/
       +/usr/local/bin:/bin:/usr/bin
 
       sudo -p 'Password: ' /bin/sh -c echo\ \$PATH
       /usr/local/bin:/bin:/usr/bin
 

以下のパスで実行されている事が分かった

/usr/local/bin:/bin:/usr/bin

実コマンドをwhichしてパスを見てみる。

which chkconfig

 => /sbin/chkconfig

serverspec側のデフォルト実行パスには「/sbin」は入ってないので実行できていなかったという事。。。