LoginSignup
5
5

More than 5 years have passed since last update.

Yii Framework: ファイル変更時にPHPUnitを自動実行してMacの通知センターに結果を表示させる

Last updated at Posted at 2013-01-17

ファイルを変更して、保存したときに PHPUnit が自動実行されるとありがたい。かつ、通知センターに結果を表示してくれればもっとありがたい。ということで試してみました。パスが Yii でのやり方になっていますが、他でもいけると思います。とりあえず最近は Yii をけっこう触っているので、Yii でのやり方で説明していきます。

まず watchr と terminal-notifier というやつをインストールします。幸いなことに自分の環境では Ruby が元々入ってたみたいで以下のようにするとインストールができました。

sudo gem install watchr
sudo gem install terminal-notifier

次に watchr を使ってファイル変更時に何をどうするかというファイルを作ります。PHPUnit + watchr + Growl という組み合わせでテストの自動実行かつ通知をするという記事はけっこうあるので、それらの記事を参考にしつつ Growl ではなく terminal-notifier を使った感じにすると以下のようなコードになります。

autounit.watchr
watch('./(.*).php')  { |m| changed(m[0]) } 

def changed(file)
  run "clear && cd tests && phpunit unit"
end

def run(cmd)
  result = `#{cmd}`
  puts result
  notify result
end

def notify(result)
  message = result.split("\n").last(3)

  title = message.find { |e| /FAILURES/ =~ e } ? "FAILURES" : "PASS"

  if title == "FAILURES"
    info = /\x1b\[37;41m\x1b\[2K(.*)/.match(message[1])[1]
  else
    if /^(Call Stack:|No tests executed!)$/ =~ result
      title = "ERROR"
      info = "Please check the error message ..."
    else
      info = /\x1b\[30;42m\x1b\[2K(.*)/.match(message[1])[1]
    end
  end

  require 'rubygems'
  require 'terminal-notifier'
  TerminalNotifier.notify(info, :title => title, :group => "phpunit")
end

.php ファイルを変更・保存したときに clear && cd tests && phpunit unit というコマンドが自動実行されて結果がターミナルと通知センターに表示される、という流れです。Autotesting with watchr, growl and PHPUnit などの記事を参考にしたんですが title が "FAILURES" かそれ以外の分岐だけでは PHP のエラーが出たときに watchr が終了してしまうみたいなので、PHPのエラーなどが含まれていれば ... という条件分岐を追加しました。あとは terminal-notifier のオプションに値を当てはめていきます。Mountain Lion Notifications from Terminal with terminal-notifier を参考にしました。また、コマンドラインで terminal-notifier -help とするとオプションの説明などが出てきます。

で、実際使うときですが、今現在は .bashrc に alias autounit='watchr /path/to/autounit.watchr' みたいなエイリアスを作って、自動実行したいなってときに コマンドライン で /protected まで移動して autounit リターンで開始するような形にしています。注意点としては watchr でファイル監視後に、新しくファイルを作成しても自動実行の対象外になるので、ある程度ファイルができてから開始したほうがいいように思います。

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5