JSpec

JSpec is a minimalistic JavaScript behavior driven development framework, providing simple installation, extremely low learning curve, absolutely no pollution to core prototypes, async request support, and incredibly sexy syntax, tons of matchers and much more.

Features

  • Highly readable

  • Framework / DOM independent

  • Rhino support

  • Async support

  • Ruby JavaScript testing server

  • Nested describes

  • Does not pollute core object prototypes

  • Cascading before/after/before_each/after_each hooks

  • Extremely simple and intuitive matcher declaration

  • Over 45 core matchers

  • Allows parens to be optional when using matchers to increase readability

  • Several helpful formatters (DOM, Console, Terminal, …)

  • Assertion graphs displaying how many, and which assertions pass or failed

  • Default / customizable evaluation contexts

  • DOM sandbox support

  • Great looking default DOM theme

  • ‘jspec` command-line utility for auto-running specs, and initializing project templates

  • Proxy or ‘Spy’ assertions

  • Shared behaviors

  • Profiling

  • Rails Integration (github.com/bhauman/jspec-rails)

  • Tiny (15 kb compressed, 1600-ish LOC)

Installation

Simply download JSpec and include JSpec.css and JSpec.js in your markup. Head over to the downloads section on Github, clone this public repo, or add JSpec as a git submodule with in your project. Alternatively JSpec is also available as a Ruby Gem (though this is not required), which also provides the ‘jspec` executable. To install as a gem simply:

$ sudo gem install visionmedia-jspec

At which point you may:

$ jspec init myproject

JSpec scripts should NOT be referenced via the <script> tag, they should be loaded using the exec method (unless you are using the grammar-less alternative). Below is an example:

...
<script>
  function runSuites() {
    JSpec
    .exec('spec.core.js')
    .exec('spec.jquery.js')
    .run({ failuresOnly : true })
    .report()
  }
</script>
<body onLoad="runSuites()">
...

You may optionally want to use sources in the /pkg directory for your project, since it includes compressed alternatives generated each release.

Example

describe 'ShoppingCart'
  before_each
    cart = new ShoppingCart
  end

  describe 'addProducts'
    it 'should add several products'
      cart.addProduct('cookie')
      cart.addProduct('icecream')
      cart.should.have 2, 'products'
    end
  end

  describe 'checkout'
    it 'should throw an error when checking out with no products'
      -{ cart.clear().checkout() }.should.throw_error EmptyCart
    end
  end
end

Grammar-less Example

JSpec’s grammar is optional, you may also use the equivalent grammar-less alternative below using pure JavaScript (when using the JSpec grammar you may also use grammar-less assertions):

JSpec.describe('ShoppingCart', function(){
  before_each(function{
    cart = new ShoppingCart
  })

  describe('addProducts', function(){
    it ('should add several products', function(){
      cart.addProducts('cookie')
      cart.addProducts('icecream')
      expect(cart).to(have, 2, 'products')
    })
  })

  describe('checkout', function(){
    it ('should throw an error when checking out with no products', function(){
      expect(function(){ cart.clear().checkout() }).to(throw_error, EmptyCart)
    })
  })
})

Options

You may alter the way JSpec operates by assigning options via the JSpec.options hash, by passing string-based option values via the query string, or passing a hash to run(). For example JSpec.options.failuresOnly = true, and ?failuresOnly=1 will both work.

  • profile bool when enabled, uses console.time() in order to display performance information in your console log as specs are completed. (DOM, Console)

  • failuresOnly bool displays only failing specs, making them quick to discover and fix (DOM, Terminal)

  • reportToId string an element id to report to when using the DOM formatter (DOM)

Matchers

* Core

- equal, be          ===
- be_a, be_an        have constructor of x
- be_an_instance_of  instanceof x
- be_at_least        >=
- be_at_most         <=
- be_null            == null
- be_empty           length of 0
- be_true            == true
- be_false           == false
- be_type            be type of x
- be_greater_than    >
- be_less_than       <
- throw_error        should throw an error, optionally supply the error string for comparison
- have               object should have n of property (person.should.have(2, 'pets'))
- have_at_least      object should have at least n of property
- have_at_most       object should have a maximum n of property
- have_within        object should have within n..n of property (person.should.have_within(1..3, 'pets')
- have_length        length of n
- have_prop          object should have property x, optionally supplying an expected value
- have_property      strict version of have_prop
- be_within          checks if n is within the range passed
- include            include substring, array element, or hash key
- match              string should match regexp x
- respond_to         property x should be a function
- eql                matches simple literals (strings, numbers) with == 
                     However composites like arrays or 'hashes' are recursively matched,
                     meaning that [1, 2, [3]].should_eql([1, 2, [3]]) will be true.

* jQuery

- have_tag, have_one    have exactly one tag   
- have_tags, have_many  have more than one tag
- have_child            have exactly one child
- have_children         have more than one child
- have_text             have plain text
- have_attr             have an attribute, with optional value
- have_type
- have_id
- have_title
- have_alt
- have_href
- have_rel
- have_rev
- have_name
- have_target
- have_value     
- have_class
- have_classes
- be_visible
- be_hidden
- be_enabled
- be_disabled
- be_selected
- be_checked

Proxy Assertions

Proxy or ‘Spy’ assertions allow you to assert that a method is called n number of times, with x arguments, returning x value. For example:

person = { getPets : function(species){ return ['izzy'] }}
person.should.receive('getPets', 'twice').with_args(an_instance_of(String))and_return(['izzy'])
person.getPets('dog') // This will pass
person.getPets()      // This will fail because we asked an instance of String

This is a useful mechanism for testing the behavior of your object, as well as how other methods may interact with it. Below is another example:

array = ['foo', 'bar']
array.should.receive('toString').and_return('foo,bar')
'array: ' + array // This line causes the spec to pass due to calling toString()

For more examples view spec/spec.matchers.js

Helpers

* Core

- wait             delay execution of a spec for the duration set (async support)
- an_instance_of   used in conjunction with the 'receive' matcher

* jQuery      

- sandbox     used to generate new DOM sandbox, using jQuery object
- element     same as invoking jQuery, just reads better and no need to worry about $ collisions
- elements    alias of element

Shared Behaviors

JSpec’s support for shared behaviors allows multiple suites or describe blocks to share common functionality. For example an Admin, would inherit all specs of User:

describe 'User'
  before
    User = function(name) { this.name = name }
    user = new User('joe')
  end

  it 'should have a name'
    user.should.have_property 'name'
  end

  describe 'Administrator'
    should_behave_like('User')

    before
      Admin = function(name) { this.name = name }
      Admin.prototype.may = function(perm){ return true }
      user = new Admin('tj')
    end

    it 'should have access to all permissions'
      user.may('edit pages').should.be_true
    end
  end
end

NOTE: both User and Administrator’s before hooks implement the ‘user’ variable

Async Support Using wait()

When using jQuery with JSpec all requests are switched to sync, allowing specs to run naturally, however when testing functionality using setTimeout, setInterval etc JSpec supplies the wait() utility to delay a spec from running:

it 'should wait for n milliseconds'
  wait(2, 'seconds')
  setTimeout(function(){
    true.should.be true
  }, 1500)
end

Hooks

Currently the following hooks are supported, and may be utilized any number of times as they are simply pushed to a stack. So for instance you may have two before_each blocks within the same scope, they will both run, but this can help keep your specs readable.

* before       run once before the suite is executed
* after        run once after the suite is executed
* before_each  run before each specification
* after_each   run after each specification

Custom Contexts

Custom contexts can be applied to supply helper methods or properties to all subsequent bodies (other hooks, or specs).

Keep in mind that when replacing the default context you will loose functionality provided by it, unless you manually merge it with your custom context.

To reset the context simply assign null to obtain the original context.

...
before
  JSpec.context = { foo : 'bar' }
end

after
  JSpec.context = null
end

it 'will work ;)'
  foo.should_equal 'bar'
end
...

Async Support

Currently only jspec.jquery.js supports async requests. JSpec uses jQuery.ajaxSetup and sets all requests to sync, which preserves execution order, and reports correctly.

it 'should load mah cookies (textfile)'
  $.post('async', function(text){
    text.should_eql 'cookies!'
  })
end

Pre-processor

The pre-processing capability of JSpec is extremely powerful. Your JavaScript code is not necessarily what it seems. For example when you seemingly invoke a object’s prototype like below:

'foobar'.should.include 'bar'

First parens are added:

'foobar'.should.include('bar')

Secondly the matcher invocation is converted to a non-polluting match() call:

JSpec.match('foobar', 'should', 'include', 'bar')

This also means instead of:

var object = { foo : 'bar' }
object.should.include 'foo'

We can do:

{ foo : 'bar' }.should.include 'foo'

Closure Literal

These are equivalent:

-{ throw 'test' }.should.throw_error
function() { throw 'test' }.should.throw_error

Inclusive Range Literal

The following expands to the array of [1,2,3,4,5]

n.should.be_within 1..5

Formatters

To change a formatter simply alter the options hash like below, assigning a new constructor, or pass it within the hash to run():

JSpec.options.formatter = JSpec.formatters.Console

OR

JSpec .exec(‘…’) .run({ formatter : JSpec.formatters.Terminal }) .report()

Custom Matchers

First lets create a simple equality matcher. In the case below JSpec is smart enough to realize this is simply a binary operator, and simply transforms this into ‘actual === expected’

JSpec.addMatchers({
  equal : '==='
})

To alias a method to keep your specs readable you may alias them like below:

JSpec.addMatchers({
  be : 'alias equal'
})

'foo'.should.equal 'foo'
true.should.be true

Matchers with string bodies implicitly return the expression value. The expanded version of the equal matcher would then be:

JSpec.addMatchers({
  equal : 'actual === expected'
})

Large matchers or those which require several parameters may wish to utilize the hash method:

JSpec.addMatchers({
  equal : { match : function(actual, expected){
    return actual === expected
  }}  
})

To keep JSpec tiny, JSpec will default to generating failure messages for you, how ever this can be explicitly defined:

JSpec.addMatchers({
  equal : { 
    match : function(actual, expected){
      return actual === expected
    },
    message : function(actual, expected, negate) {
      return 'a message here'
    }
  }
})

JSpec Command-line Utility

When installed as a Ruby Gem, the ‘jspec` executable will become available, allowing you to initialize project templates quickly, as well as auto-testing specifications when a file is altered.

Initialize JSpec-driven project template in directory ‘myproject’:

$ jspec init myproject

Once within ‘myproject’ start testing by executing:

$ jspec

For additional usage execute:

$ jspec help

Or for specific usage:

$ jspec help run

Rhino

JSpec provides transparent support for Rhino, while using the Terminal formatter. Simply create a JavaScript file with contents similar to below, and then execute the command following it:

load('lib/jspec.js')

JSpec
.exec('spec/spec.grammar.js')
.exec('spec/spec.core.js')
.run({ formatter : JSpec.formatters.Terminal, failuresOnly : true })
.report()

Initialize project with:

$ jspec init myproject --template rhino

Run with:

$ jspec run --rhino

Or bind (automated testing):

$ jspec --rhino

Server

The Ruby JavaScript testing server included with JSpec simply runs the spec suites within each browser you specify, while reporting result back to the terminal. It is essentially the same as using the DOM formatter and auto-testing each browser, however results are centralized to the terminal, removing the need to manually view each browser’s output.

Initialize project with:

$ jspec init myproject --template server

Run with:

$ jspec run --server

More Information

License

(The MIT License)

Copyright © 2008 - 2009 TJ Holowaychuk <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ‘Software’), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.