Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
copious documentation and examples, following tim's lead
  • Loading branch information
Nick Kallen committed May 12, 2008
1 parent 3a278fe commit 6504f7a
Show file tree
Hide file tree
Showing 17 changed files with 535 additions and 177 deletions.
68 changes: 68 additions & 0 deletions EXAMPLE.html
@@ -0,0 +1,68 @@
<html>
<!--
This file is a fully-functioning example test case. Try opening this file in Firefox, Safari,
or Internet Explorer to see what a running test looks like.
This file demonstrates the the components involved in writing a simple test, such as:
* The necessary HTML to run a test (with the required <script> and <link rel="stylesheet"> tags),
* A "custom matcher" (i.e., a custom assertion) to make your tests more readable,
* And, a simple test with the necessary boiler-plate code to get you up and running.
Typically, these components are separated out into multiple files. To see what a more typical suite
of tests look like, look at the larger example in the examples/ directory.
-->
<head>
<!-- These are all of the necessary javascript and css files required to run your tests -->
<script src="lib/jquery-1.2.3.js"></script>
<script src="lib/jquery.fn.js"></script>
<script src="lib/jquery.print.js"></script>
<script src="lib/screw.builder.js"></script>
<script src="lib/screw.matchers.js"></script>
<script src="lib/screw.events.js"></script>
<script src="lib/screw.behaviors.js"></script>
<link rel="stylesheet" href="lib/screw.css">

<script type="text/javascript">
// Here is the system under test (SUT)--that is, your application code that you would like
// to test.
function foo() {
return 2;
}
</script>

<script type="text/javascript">
// Here is a Custom Matcher. A custom matcher is a custom assertion,
// tailored to your application; these help to make your tests more readable.
Screw.Matchers["be_even"] = {
match: function(expected, actual) {
return actual % 2 == 0;
},
failure_message: function(expected, actual, not) {
return 'expected ' + $.print(actual) + (not ? ' not' : '') + ' to be even';
}
}
</script>

<script type="text/javascript">
// Here is a sample test. Note that all tests are wrapped in
// "Screw.Unit(function() { ... })".
Screw.Unit(function() {
// Tests are organized into 'describes' and 'its', following the style of RSpec.
describe("foo", function() {
it("returns 2", function() {
// 'equal' is one among many matchers provided with the Screw.Unit distribution. It
// is smart enough to compare arrays, objects, and primitives.
expect(foo()).to(equal, 2);
});
});

describe("an undefined variable", function() {
// Here is a use of the custom matcher defined above.
it("is not defined", function() {
expect(2).to(be_even);
expect(3).to_not(be_even);
});
});
});
</script>
</head>
<body></body>
</html>
22 changes: 22 additions & 0 deletions LICENSE
@@ -0,0 +1,22 @@
Copyright (c) 2008 Nick Kallen

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.
246 changes: 223 additions & 23 deletions README.markdown
@@ -1,14 +1,14 @@
Screw.Unit is a Behavior-Driven Testing Framework for Javascript written by Nathan Sobo and Nick Kallen. It features nested describes. Its goals are to provide: Screw.Unit is a Behavior-Driven Testing Framework for Javascript. It features nested describes. Its goals are to provide:


* a DSL for elegant, readable, organized specs; * a DSL for elegant, readable, organized specs;
* an interactive runner which can execute focused specs and describes; * an interactive runner that can execute focused specs and describes;
* and brief, extensible source-code. * and brief, extensible source-code.


# What it is # What it is


![Test Runner](http://s3.amazonaws.com/assets.pivotallabs.com/87/original/runner.png) ![Test Runner](http://s3.amazonaws.com/assets.pivotallabs.com/87/original/runner.png)


The testing language is inspired by JSpec (and Rspec, obviously). Consider, The testing language is closure-based. Consider,


describe("Matchers", function() { describe("Matchers", function() {
it("invokes the provided matcher on a call to expect", function() { it("invokes the provided matcher on a call to expect", function() {
Expand All @@ -17,7 +17,7 @@ The testing language is inspired by JSpec (and Rspec, obviously). Consider,
}); });
}); });


A key feature of Screw.Unit are nested `describes` and the cascading `before` behavior that entails: A key feature of Screw.Unit are nested `describes` and the cascading `before` (and `after`) behavior that entails:


describe("a nested describe", function() { describe("a nested describe", function() {
var invocations = []; var invocations = [];
Expand All @@ -36,12 +36,213 @@ A key feature of Screw.Unit are nested `describes` and the cascading `before` be
}); });
}); });
}); });


# The Runner

The Screw.Unit runner is pretty fancy, supporting focused `describes` and focused `its`: The Screw.Unit runner is pretty fancy, supporting focused `describes` and focused `its`:


![Focused Runner](http://s3.amazonaws.com/assets.pivotallabs.com/86/original/focused.png) ![Focused Runner](http://s3.amazonaws.com/assets.pivotallabs.com/86/original/focused.png)


You can [download the source](http://github.com/nkallen/screw-unit/tree/master) from Github. Please see the included spec (`screwunit_spec.js`) to get up and running. Click on a `describe` or `it` to run just those tests.

# Global Befores and Afters

A global `before` is a `before` block run before all tests in a test suite, regardless of their nesting. This is often useful to reset global variables, or blank-out DOM nodes before each test is run. Put this at the top of the your suite file or in your spec helper.

Screw.Unit(function() {
before(function() { ... });
});

Note that you can have any number of `Screw.Unit(...)` blocks in one file. Thus, you can have multiple global `befores` and `afters`.

# Custom Matchers

A custom matcher is a custom assertion specifically tailored to your application. These are helpful in increasing the readability and declarativity of your tests. To create a custom matcher, fill in the blanks for this code:

Screw.Matchers["be_even"] = {
match: function(expected, actual) {
return actual % 2 == 0;
},
failure_message: function(expected, actual, not) {
return 'expected ' + $.print(actual) + (not ? ' not' : '') + ' to be even';
}
}

You can invoke this matcher as follows: `expect(2).to(be_even)`.

# The Anatomy of Test Infrastructure

Typical test infrastructure spans multiple files:

* A `suite.html` file that has the necessary html, script tags, and link tags, to include your source code as well as the test infrastructure.
* A `spec_helper.js` file with global `before` and `after` blocks.
* A set of custom matchers.
* Your individual tests.

The file structure will typically look like:

spec/
suite.html
spec_helper.js
matchers/
a_matcher.js
another_matcher.js
models/
a_spec.js
another_spec.js
views/
yet_another_spec.js

The `models` and `views` directories are here only for comparison. As a general rule, mirror the file structure of your source code in your spec directory. For example, if you have an MVC application and you organize your source code into `models`, `views`, and `controllers` directories, have parallel directories in your spec/ directory, with tests for your models, views, and controllers in their respective directories.

# Writing Good Tests

A great test maximizes these features:

* it provides **documentation**, explaining the intended functioning of the system as well as how the source code works;
* it supports **ongoing development**, as you bit-by-bit write a failing test and make it pass;
* it supports **refactoring** and **prevents regression**;
* and it **requires little modification** as the implementation of the system changes, especially changes to unrelated code.

This section focuses principally on tests as documentation. **To provide documentation, as well as support future modification, a test should be readable and well organized.** Here are some recommendations on how to do it.

## Use Nested Describes to Express Context

Often, when you test a system (a function, an object), it behaves differently in different contexts. Use **nested** describes liberally to express the context under which you make an assertion.

describe("Caller#prioritize", function() {
describe("when there are two callers in the queue", function() {
describe("and one caller has been waiting longer than another", function() {
...
});
});
});

In addition to using nested describes to express context, use them to organize tests by the structural properties of your source code and programming language. In Javascript this is typically prototype and function. A parent describe for a prototype contains nested describes for each of its methods. If you have cross-cutting concerns (e.g., related behavior that spans across methods or prototypes), use a describe to group them conceptually.

describe("Car", function() {
describe("#start", function() {
});
describe("#stop", function() {
});
describe("callbacks", function() {
describe("after_purchase", function() {
});
});
describe("logging", function() {
});
});

In this example, one parent `describe` is used for all `Car` behavior. There is a describe for each method. Finally, cross-cutting concerns like callbacks and logging are grouped because of their conceptual affinity.

# Test Size

Individual tests should be short and sweet. It is sometimes recommended to make only one assertion per test:

it("chooses the caller who has been waiting the longest", function() {
expect(Caller.prioritize()).to(equal, caller_waiting_the_longest);
});

According to some, the ideal test is one line of code. In practice, it may be excessive to divide your tests to be this small. At ten lines of code (or more), a test is difficult to read quickly. Be pragmatic, bearing in mind the aims of testing.

Although one assertion per test is a good rule of thumb, feel free to violate the rule if equal clarity and better terseness is achievable:

it("returns the string representation of the boolean", function() {
expect($.print(true)).to(equal, 'true');
expect($.print(false)).to(equal, 'false');
});

Two tests would be overkill in this example.

## Variable Naming

Name variables descriptively, especially ones that will become expected values in assertions. `caller_waiting_the_longest` is better than `c1`.

## Dividing code between tests and `befores`

If there is only one line of setup and it is used in only one test, it may be better to include the setup in the test itself:

it("decrements the man's luck by 5", function() {
var man = new Man({luck: 5});
cat.cross_path(man);
expect(man.luck()).to(equal, 0);
});

But in general, it's nice to keep setup code in `before` blocks, especially if the setup can be shared across tests.

describe('Man', function() {
var man;
before(function() {
man = new Man({luck: 5});
});

describe('#decrement_luck', function() {
it("decrements the luck field by the given amount", function() {
man.decrement_luck(3);
expect(man.luck()).to(equal, 2)
});
});
...
});

## Preconditions

It is ideal, if there is any chance that your preconditions are non-obvious, to make precondition asserts in your test. The last example, were it more complicated, might be better written:

it("decrements the luck field by the given amount", function() {
expect(man.luck()).to(equal, 5);

man.decrement_luck(3);
expect(man.luck()).to(equal, 2)
});

Whitespace, as seen here, can be helpful in distinguishing setup and preconditions from the system under test (SUT) and its assertions. It is nice to be consistent in your use of whitespace (e.g., "always follow a group of preconditions by a newline"). But it is better to use whitespace as makes the most sense given the context. As with everything in life, do it consciously and deliberately, but change your mind frequently.

## Behavioral Testing

Behavioral testing, that is, asserting that certain functions are called rather than certain values returned, is best done with closures. The dynamic nature of JavaScript makes mocking frameworks mostly unnecessary.

it("invokes #decrement_luck", function() {
var decrement_luck_was_called = false;
man.decrement_luck = function(amount) {
decrement_luck_was_called = true;
});
cat.cross_path(man);
expect(decrement_luck_was_called).to(equal, true);
});

# How to Test the DOM

The simplest way to test the DOM is to have a special DOM node in your `suite.html` file. Have all tests insert nodes into this node; have a global `before` reset the node between tests.

In `suite.html`:

<div id="dom_test"></div>

In `spec_helper.js`:

Screw.Unit(function() {
before(function() {
document.getElementById('dom_test').innerHTML = ''; // but use your favorite JS library here.
});
});

In `some_spec.js`:

describe("something that manipulates the DOM", function() {
it("is effortless to test!", function() {
var dom_test = document.getElementById('dom_test');
dom_test.innerHTML = 'awesome';
expect(dom_test.innerHTML).to(equal, 'awesome');
});
});

A Javascript library like jQuery, Prototype, or YUI is a essential for testing events.


# Implementation Details # Implementation Details


Expand Down Expand Up @@ -75,22 +276,6 @@ Bind behaviors by passing a hash (see the previous example). Using CSS3 selector
$('.describe, .it').fn({...}); // applies to both describe and its $('.describe, .it').fn({...}); // applies to both describe and its
$('.describe .describe').fn({...}); // applies to nested describes only $('.describe .describe').fn({...}); // applies to nested describes only


A typical Concrete Javascript Application is divided into 4 aspects:

* a DOM data model,
* CSS bound to DOM elements,
* asynchronous events bound to DOM elements (`click`, `mouseover`), etc.,
* synchronous behaviors bound to DOM elements (`run` and `parent` in the above example).

The Concrete style is particularly well-suited to Screw.Unit; to add the ability to run a focused spec, we simply bind a click event to an `it` or a `describe`, which runs itself:

$('.describe, .it')
.click(function() {
$(this).fn('run');
})

Anyway, more details about Effen / Concrete Javascript in a later post.

# Extensibility # Extensibility


Screw.Unit is designed from the ground-up to be extensible. For example, to add custom logging, simply subscribe to certain events: Screw.Unit is designed from the ground-up to be extensible. For example, to add custom logging, simply subscribe to certain events:
Expand All @@ -101,7 +286,22 @@ Screw.Unit is designed from the ground-up to be extensible. For example, to add
.bind('passed', function() {...}) .bind('passed', function() {...})
.bind('failed', function(e, reason) {...}) .bind('failed', function(e, reason) {...})


There are also events for the `loading` and `loaded` test code code, as well as just `before` and just `after` all tests are run:

$(Screw)
.bind('loading', function() {...})
.bind('loaded', function() {...})
.bind('before', function() {...})
.bind('after', function() {...})

# Download

You can [download the source](http://github.com/nkallen/screw-unit/tree/master) from Github. There is are plenty of examples in the distribution.

# Thanks to # Thanks to


* Nathan Sobo * Nathan Sobo
* Yehuda Katz * Yehuda Katz
* Brian Takita
* Aman Gupta
* Tim Connor
2 changes: 0 additions & 2 deletions TODO

This file was deleted.

0 comments on commit 6504f7a

Please sign in to comment.