coffeescriptでTDD/BDDをする場合の選択肢としては、jasimine-nodeなどがあるが、今回はmochaとその補完モジュールのchaiをためしてみる
インストール
$ sudo npm install -g mocha
$ sudo npm install -g chai
今回のファイル構成は下記。例としてTaskというクラスを作る
.
├── Cakefile
├── src
│ └── task.coffee
└── tests
└── task_test.coffee
テストファイルを書く。Jasmineと同じようなexpectスタイルと、全てのObjectにshouldメソッドを追加するRSpec的なスタイルと両方使える
tests/task_test.coffee
chai = require 'chai'
expect = chai.expect
chai.should()
# add should method to Object.prototype
Task = require("../src/task").Task
describe 'Task',->
t = null
before ->
t = new Task("foo bar")
it "expects true is true like Jasmine", ->
expect(true).be.true
it "should be true like RSpec", ->
true.should.be.true
it "should rutern item string with toString",->
t.toString().should.equal("foo bar")
it "should return true with #did after done", ->
t.did.should.not.be.true
t.done()
t.did.should.be.true
実装ファイル
src/task.coffee
root = exports ? window
class root.Task
did: false
constructor: (item) ->
@item = item
toString: ->
@item
done: ->
@did = true
テストを実行する
$ export NODE_PATH=/usr/local/lib/node_modules
$ mocha --compilers coffee:coffee-script tests/
オプションが面倒なのでCakefileを書いておく。
Cakefile
process.env.NODE_PATH = '/usr/local/lib/node_modules'
cp = require 'child_process'
task 'test','run tests', ->
cp.spawn "mocha"
,[ "--compilers","coffee:coffee-script","tests/"]
,{ stdio: 'inherit' }
すると下記のように実行できるようになる
$ cake test