LoginSignup
1
1

More than 5 years have passed since last update.

grunt watch で変更したファイルに関連するテストだけ実行する

Last updated at Posted at 2013-12-07

たとえば、 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 で実行間隔を絞ってるのがポイントです。

1
1
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
1
1