Add custom matcher of serverspec v2

Add custom matcher of serverspec v2

userリソースbe_locked マッチャーを追加するコードをserverspec version2用に書き直す作業をした覚書き (既存のリソースタイプにマッチャーを追加する覚書き)

version1

module Serverspec
  module Type
    class User
      def locked?
        backend.check_user_locked(@name)
      end
    end
  end
end

module SpecInfra
  module Command
    class Base
      def check_user_locked(user)
        "passwd -S #{escape(user)} | grep -- ' LK '"
      end
    end
  end
end

version2

module Serverspec::Type
  class User < Base
    def locked?
      @runner.check_user_locked(@name)
    end
  end
end

class Specinfra::Command::Base::User < Specinfra::Command::Base
  class << self
    def check_locked(user)
      "passwd -S #{escape(user)} | grep -- ' LK '"
    end
  end
end

動作確認用コード

require 'serverspec'

set :backend, :exec

describe user('licorice') do
  it { should_not be_locked }
end

describe user('licorice') do
  it { should be_locked }
end

module Serverspec::Type
  class User < Base
    def locked?
      @runner.check_user_locked(@name)
    end
  end
end

class Specinfra::Command::Base::User < Specinfra::Command::Base
  class << self
    def check_locked(user)
      "passwd -S #{escape(user)} | grep -- ' LK '"
    end
  end
end

実行

$ bundle exec rspec test.rb

User "licorice"
  should not be locked

User "licorice"
  should be locked (FAILED - 1)

Failures:

  1) User "licorice" should be locked
     Failure/Error: it { should be_locked }
       expected `User "licorice".locked?` to return true, got false
       /bin/sh -c passwd\ -S\ licorice\ \|\ grep\ --\ \'\ LK\ \'

     # ./test.rb:10:in `block (2 levels) in <top (required)>'

Finished in 0.07063 seconds (files took 0.30355 seconds to load)
2 examples, 1 failure

Failed examples:

参考書籍

Serverspec(アホ毛本)