たとえば、 app/models/hoge.coffee
を編集したときに、 test/app/models/hoge_test.coffee
だけ、テストを実行したいときってありますよね。自分は以下のような感じでやっています。
Gruntfile.coffee
module.exports = (grunt) ->
grunt.initConfig
pkg: '<json:package.json>'
mochacli:
options:
timeout: 3000
ui: 'bdd'
reporter: 'spec'
compilers: ['coffee:coffee-script']
app:
src: 'test/app/**/*_test.coffee'
watch:
test:
options:
spawn: false
files: [
'app/**/*.coffee'
'test/app/**/*.coffee'
]
grunt.loadTasks 'tasks'
grunt.loadNpmTasks 'grunt-mocha-cli'
grunt.loadNpmTasks 'grunt-contrib-watch'
tasks/watch-test.coffee
fs = require 'fs'
_ = require 'lodash'
module.exports = (grunt) ->
lastModified = 0
runAllTests = _.throttle ->
grunt.task.run 'mochacli:app'
, 30000
grunt.event.on 'watch', _.throttle((action, filepath, target) ->
return unless target is 'test'
currentTime = new Date().getTime()
if currentTime - lastModified < 2000
runAllTests()
return
lastModified = currentTime
if _.startsWith(filepath, 'app')
testpath = 'test/' + filepath.replace(/\.coffee$/, '_test.coffee')
else
testpath = filepath
return unless fs.existsSync(testpath)
grunt.config 'mochacli.changed.src', testpath
grunt.task.run 'mochacli:changed'
), 200
短い間隔でファイルを更新すると、テスト全実行されたり、Git で branch を切り替えたりしたときに、たくさんテストが実行されないように、_.throttle で実行間隔を絞ってるのがポイントです。