CSS

mini BDD Framework in CoffeeScript

Rails 3.1 is default supporting Coffee-Script,

This might be controversial, but basically I think it is a right move,
since rails development philosophy is always simplify developer's life.
And coffee script sure is.


compare the following code with javascript and coffee script:
describe('spec in javascript', function(){
  it('should return true in javascript',function(){
    return 1===1;
  });
});

//in coffee script
describe 'spec in coffeescript', ->
  it 'should return true in coffeescript',->
    1 is 1

You can see how the syntax has been simplified and easy to read.

Inspired by A unit test framework in 44 lines of ruby, I want to write a test framework in coffeescript to show the good of it.

Here's the work:
dsl =
  tests : {}
  it : (description,test) ->
    @tests[description] = test
  parse:(block)->
    block.call(dsl)
    @tests

class Executor
  constructor: (@description,@tests) ->
  tests : {}
  success : 0
  fail : 0
  count : 0
  run:()->
    console.log(@description + " ::")
    @execute desc,test for desc,test of @tests
    console.log("Executed #{@count} tests: #{@success} success, #{@fail} fail")

  execute : (desc,test) ->
    test_result = test()
    if test_result is yes than @success += 1 else @fail += 1
    @count += 1
    console.log(" --"+ desc + " is "+ test_result)

exports.describe = (description,block) ->
  executor = new Executor(description,dsl.parse(block))
  executor.run()

with the following testcase

spec = require './nspec'

spec.describe 'hello coffee test', ->

  @it 'should be true', ->
    1 is 1

  @it 'should fail', ->
    1 is 2

Basically the describe function contains all tests in callback,
and will parse all the testcase by
block.call(dsl)
which inject the dsl functions as the "this" object in block, and the "it" syntax will collect the test functions to a map object.
afterward, Executor will execute all tests and print out results.

During the implementation, I can't find the way to remove that nasty @ before test function 'it'
without declaring global. I am still working on it, there's a solution that you can execute test
by calling node.js child_process "coffee spec.coffee"(from coffee-spec), but that will be too complex for this. Jasmine didn't have this problem, let me know if anyone got the answer, or I will figure it out later :p.

1 comment: