Skip to content
Myr

Removed specs

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Tj Holowaychuk · committed by Tj Holowaychuk · parent c75105e · Browse files · 53 files+0 added−4821 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

53 files+0 added−4821 removed

  • tests:+0 added−4821 removed

53 files+0 added−4821 removed

deleted:spec/fixtures/partials/article.html.ejs-9 removed
1<ul>2 <% if (__isFirst__) { %>3 <li class="first"><%= article %></li>4 <% } else if (__isLast__) { %>5 <li class="last"><%= article %></li>6 <% } else { %>7 <li class="<%= __index__ %>"><%= article %></li>8 <% } %>9</ul>
deleted:spec/fixtures/partials/article.html.haml-7 removed
1%ul2 - if (__isFirst__)3 %li.first= article4 - if (__isLast__)5 %li.last= article6 - if (!__isLast__ && !__isFirst__)7 %li{ class: __index__ }= article
deleted:spec/fixtures/partials/item.html.ejs-1 removed
1<li><%= item %></li>
deleted:spec/fixtures/partials/item.html.haml-1 removed
1%li= item
deleted:spec/fixtures/partials/video.html.ejs-1 removed
1<li><%= vid %></li>
deleted:spec/fixtures/partials/video.html.haml-1 removed
1%li= vid
deleted:spec/fixtures/article.html.haml-1 removed
1%h2!= this.name
deleted:spec/fixtures/hello.html.haml-1 removed
1%h2 Hello
deleted:spec/fixtures/helpers-layout.html.haml-1 removed
1Testing
deleted:spec/fixtures/helpers.html.haml-1 removed
1%span= _('Hello world')
deleted:spec/fixtures/layout-helper.html.haml-1 removed
1%span= _(body)
deleted:spec/fixtures/layout-user.html.haml-2 removed
1%title= "Viewing " + name2%body!= body
deleted:spec/fixtures/layout.html.ejs-1 removed
1<p><%= body %></p>
deleted:spec/fixtures/layout.html.haml-2 removed
1%html2 %body!= body
deleted:spec/fixtures/list.html.ejs-5 removed
1<ul>2 <% for (var i in items) { %>3 <%= this.partial("item.html.ejs", { locals: { item: items[i] }}) %>4 <% } %>5</ul>
deleted:spec/fixtures/list.html.haml-3 removed
1%ul2 - each item in items3 != this.partial('item.html.haml', { locals: { item: item }})
deleted:spec/fixtures/page.html.haml-2 removed
1%title= this.title2%body!= body
deleted:spec/fixtures/user.html.ejs-2 removed
1<h1><%= this.name %></h1>2<p><%= this.email %></p>
deleted:spec/fixtures/user.html.haml-2 removed
1%h1= name2%p= email
deleted:spec/fixtures/user.html.invalid
deleted:spec/fixtures/user.json-4 removed
1{2 "name": "tj",3 "email": "tj@vision-media.ca"4}
deleted:spec/lib/images/bg.pngbinary

A binary file, deleted.

deleted:spec/lib/images/hr.pngbinary

A binary file, deleted.

deleted:spec/lib/images/loading.gifbinary

A binary file, deleted.

deleted:spec/lib/images/sprites.bg.pngbinary

A binary file, deleted.

deleted:spec/lib/images/sprites.pngbinary

A binary file, deleted.

deleted:spec/lib/images/vr.pngbinary

A binary file, deleted.

deleted:spec/lib/jspec.css-149 removed
1body.jspec {2 margin: 45px 0;3 font: 12px "Helvetica Neue Light", "Lucida Grande", "Calibri", "Arial", sans-serif;4 background: #efefef url(images/bg.png) top left repeat-x;5 text-align: center;6}7#jspec {8 margin: 0 auto;9 padding-top: 30px;10 width: 1008px;11 background: url(images/vr.png) top left repeat-y;12 text-align: left;13}14#jspec-top {15 position: relative;16 margin: 0 auto;17 width: 1008px;18 height: 40px;19 background: url(images/sprites.bg.png) top left no-repeat;20}21#jspec-bottom {22 margin: 0 auto;23 width: 1008px;24 height: 15px;25 background: url(images/sprites.bg.png) bottom left no-repeat;26}27#jspec .loading {28 margin-top: -45px;29 width: 1008px;30 height: 80px;31 background: url(images/loading.gif) 50% 50% no-repeat;32}33#jspec-title {34 position: absolute;35 top: 15px;36 left: 20px;37 width: 160px;38 font-size: 22px;39 font-weight: normal;40 background: url(images/sprites.png) 0 -126px no-repeat;41 text-align: center;42}43#jspec-title em {44 font-size: 10px;45 font-style: normal;46 color: #BCC8D1;47}48#jspec-report * {49 margin: 0;50 padding: 0;51 background: none;52 border: none;53}54#jspec-report {55 padding: 15px 40px;56 font: 11px "Helvetica Neue Light", "Lucida Grande", "Calibri", "Arial", sans-serif;57 color: #7B8D9B;58}59#jspec-report.has-failures {60 padding-bottom: 30px;61}62#jspec-report .hidden {63 display: none;64}65#jspec-report .heading {66 margin-bottom: 15px;67}68#jspec-report .heading span {69 padding-right: 10px;70}71#jspec-report .heading .passes em {72 color: #0ea0eb;73}74#jspec-report .heading .failures em {75 color: #FA1616;76}77#jspec-report table {78 font-size: 11px;79 border-collapse: collapse;80}81#jspec-report td {82 padding: 8px;83 text-indent: 30px;84 color: #7B8D9B;85}86#jspec-report tr.body {87 display: none;88}89#jspec-report tr.body pre {90 margin: 0;91 padding: 0 0 5px 25px;92}93#jspec-report tr.even:hover + tr.body, 94#jspec-report tr.odd:hover + tr.body {95 display: block;96}97#jspec-report tr td:first-child em {98 display: block;99 clear: both;100 font-style: normal;101 font-weight: normal;102 color: #7B8D9B;103}104#jspec-report tr.even:hover, 105#jspec-report tr.odd:hover {106 text-shadow: 1px 1px 1px #fff;107 background: #F2F5F7;108}109#jspec-report td + td {110 padding-right: 0;111 width: 15px;112}113#jspec-report td.pass {114 background: url(images/sprites.png) 3px -7px no-repeat;115}116#jspec-report td.fail {117 background: url(images/sprites.png) 3px -158px no-repeat;118 font-weight: bold;119 color: #FC0D0D;120}121#jspec-report td.requires-implementation {122 background: url(images/sprites.png) 3px -333px no-repeat;123}124#jspec-report tr.description td {125 margin-top: 25px;126 padding-top: 25px;127 font-size: 12px;128 font-weight: bold;129 text-indent: 0;130 color: #1a1a1a;131}132#jspec-report tr.description:first-child td {133 border-top: none; 134}135#jspec-report .assertion {136 display: block;137 float: left;138 margin: 0 0 0 1px;139 padding: 0;140 width: 1px;141 height: 5px;142 background: #7B8D9B;143}144#jspec-report .assertion.failed {145 background: red;146}147.jspec-sandbox {148 display: none;149}
deleted:spec/lib/jspec.growl.js-115 removed
12// JSpec - Growl - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)34;(function(){5 6 Growl = {7 8 // --- Version9 10 version: '1.0.0',11 12 /**13 * Execute the given _cmd_, returning an array of lines from stdout.14 *15 * Examples:16 *17 * Growl.exec('growlnotify', '-m', msg)18 *19 * @param {string ...} cmd20 * @return {array}21 * @api public22 */2324 exec: function(cmd) {25 var lines = [], line26 with (JavaImporter(java.lang, java.io)) {27 var proccess = Runtime.getRuntime().exec(Array.prototype.slice.call(arguments))28 var stream = new DataInputStream(proccess.getInputStream())29 while (line = stream.readLine())30 lines.push(line + '')31 stream.close() 32 }33 return lines34 },35 36 /**37 * Return the extension of the given _path_ or null.38 *39 * @param {string} path40 * @return {string}41 * @api private42 */43 44 extname: function(path) {45 return path.lastIndexOf('.') != -1 ? 46 path.slice(path.lastIndexOf('.') + 1, path.length) :47 null48 },4950 /**51 * Version of the 'growlnotify' binary.52 *53 * @return {string}54 * @api private55 */5657 binVersion: function() {58 try { return this.exec('growlnotify', '-v')[0].split(' ')[1] } catch (e) {}59 },6061 /**62 * Send growl notification _msg_ with _options_.63 *64 * Options:65 *66 * - title Notification title67 * - sticky Make the notification stick (defaults to false)68 * - name Application name (defaults to growlnotify)69 * - image70 * - path to an icon sets --iconpath71 * - path to an image sets --image72 * - capitalized word sets --appIcon73 * - filename uses extname as --icon74 * - otherwise treated as --icon75 *76 * Examples:77 *78 * Growl.notify('New email')79 * Growl.notify('5 new emails', { title: 'Thunderbird' })80 *81 * @param {string} msg82 * @param {options} hash83 * @api public84 */8586 notify: function(msg, options) {87 options = options || {}88 var args = ['growlnotify', '-m', msg]89 if (!this.binVersion()) throw new Error('growlnotify executable is required')90 if (image = options.image) {91 var flag, ext = this.extname(image)92 flag = flag || ext == 'icns' && 'iconpath'93 flag = flag || /^[A-Z]/.test(image) && 'appIcon'94 flag = flag || /^png|gif|jpe?g$/.test(ext) && 'image'95 flag = flag || ext && (image = ext) && 'icon'96 flag = flag || 'icon'97 args.push('--' + flag, image)98 }99 if (options.sticky) args.push('--sticky')100 if (options.name) args.push('--name', options.name)101 if (options.title) args.push(options.title)102 this.exec.apply(this, args)103 }104 }105 106 JSpec.include({107 name: 'Growl',108 reporting: function(options){109 var stats = JSpec.stats110 if (stats.failures) Growl.notify('failed ' + stats.failures + ' assertions', { title: 'JSpec'})111 else Growl.notify('passed ' + stats.passes + ' assertions', { title: 'JSpec' })112 }113 })114 115})()
deleted:spec/lib/jspec.jquery.js-79 removed
12// JSpec - jQuery - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)34JSpec5.requires('jQuery', 'when using jspec.jquery.js')6.include({7 name: 'jQuery',8 9 // --- Initialize10 11 init : function() {12 jQuery.ajaxSetup({ async: false })13 },14 15 // --- Utilities16 17 utilities : {18 element: jQuery,19 elements: jQuery,20 sandbox : function() {21 return jQuery('<div class="sandbox"></div>')22 }23 },24 25 // --- Matchers26 27 matchers : { 28 have_tag : "jQuery(expected, actual).length === 1",29 have_one : "alias have_tag",30 have_tags : "jQuery(expected, actual).length > 1",31 have_many : "alias have_tags",32 have_any : "alias have_tags",33 have_child : "jQuery(actual).children(expected).length === 1",34 have_children : "jQuery(actual).children(expected).length > 1",35 have_text : "jQuery(actual).text() === expected",36 have_value : "jQuery(actual).val() === expected",37 be_enabled : "!jQuery(actual).attr('disabled')",38 have_class : "jQuery(actual).hasClass(expected)",39 be_animated : "jQuery(actual).queue().length > 0", 40 41 be_visible : function(actual) {42 return jQuery(actual).css('display') != 'none' &&43 jQuery(actual).css('visibility') != 'hidden' &&44 jQuery(actual).attr('type') != 'hidden'45 },46 47 be_hidden : function(actual) {48 return !JSpec.does(actual, 'be_visible')49 },50 51 have_classes : function(actual) {52 return !JSpec.any(JSpec.toArray(arguments, 1), function(arg){53 return !JSpec.does(actual, 'have_class', arg)54 })55 },5657 have_attr : function(actual, attr, value) {58 return value ? jQuery(actual).attr(attr) == value:59 jQuery(actual).attr(attr)60 },61 62 have_event_handlers : function(actual, expected) {63 return jQuery(actual).data('events') ?64 jQuery(actual).data('events').hasOwnProperty(expected) :65 false66 },67 68 'be disabled selected checked' : function(attr) {69 return 'jQuery(actual).attr("' + attr + '")'70 },71 72 'have type id title alt href src sel rev name target' : function(attr) {73 return function(actual, value) {74 return JSpec.does(actual, 'have_attr', attr, value)75 }76 }77 }78})79
deleted:spec/lib/jspec.js-1893 removed
12// JSpec - Core - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)34;(function(){56 JSpec = {7 version : '4.3.2',8 assert : true,9 cache : {},10 suites : [],11 modules : [],12 allSuites : [],13 sharedBehaviors: [],14 matchers : {},15 stubbed : [],16 options : {},17 request : 'XMLHttpRequest' in this ? XMLHttpRequest : null,18 stats : { specs: 0, assertions: 0, failures: 0, passes: 0, specsFinished: 0, suitesFinished: 0 },1920 /**21 * Default context in which bodies are evaluated.22 *23 * Replace context simply by setting JSpec.context24 * to your own like below:25 *26 * JSpec.context = { foo : 'bar' }27 *28 * Contexts can be changed within any body, this can be useful29 * in order to provide specific helper methods to specific suites.30 *31 * To reset (usually in after hook) simply set to null like below:32 *33 * JSpec.context = null34 *35 */3637 defaultContext : {38 39 /**40 * Return an object used for proxy assertions. 41 * This object is used to indicate that an object42 * should be an instance of _object_, not the constructor43 * itself.44 *45 * @param {function} constructor46 * @return {hash}47 * @api public48 */49 50 an_instance_of : function(constructor) {51 return { an_instance_of : constructor }52 },53 54 /**55 * Load fixture at _path_.56 *57 * Fixtures are resolved as:58 *59 * - <path>60 * - <path>.html61 *62 * @param {string} path63 * @return {string}64 * @api public65 */66 67 fixture : function(path) {68 if (JSpec.cache[path]) return JSpec.cache[path]69 return JSpec.cache[path] = 70 JSpec.tryLoading(JSpec.options.fixturePath + '/' + path) ||71 JSpec.tryLoading(JSpec.options.fixturePath + '/' + path + '.html')72 },73 74 /**75 * Load json fixture at _path_.76 *77 * JSON fixtures are resolved as:78 *79 * - <path>80 * - <path>.json81 *82 * @param {string} path83 * @return {object}84 * @api public85 */86 87 json_fixture: function(path) {88 if (!JSpec.cache['json:' + path])89 JSpec.cache['json:' + path] =90 JSpec.tryLoading(JSpec.options.fixturePath + '/' + path) ||91 JSpec.tryLoading(JSpec.options.fixturePath + '/' + path + '.json')92 try {93 return eval('(' + JSpec.cache['json:' + path] + ')')94 } catch (e) {95 throw 'json_fixture("' + path + '"): ' + e96 }97 }98 },99100 // --- Objects101 102 reporters : {103 104 /**105 * Report to server.106 * 107 * Options:108 * - uri specific uri to report to.109 * - verbose weither or not to output messages110 * - failuresOnly output failure messages only111 *112 * @api public113 */114 115 Server : function(results, options) {116 var uri = options.uri || 'http://' + window.location.host + '/results'117 JSpec.post(uri, {118 stats: JSpec.stats,119 options: options,120 results: map(results.allSuites, function(suite) {121 if (suite.isExecutable())122 return {123 description: suite.description,124 specs: map(suite.specs, function(spec) {125 return {126 description: spec.description,127 message: !spec.passed() ? spec.failure().message : null,128 status: spec.requiresImplementation() ? 'pending' :129 spec.passed() ? 'pass' :130 'fail',131 assertions: map(spec.assertions, function(assertion){132 return {133 passed: assertion.passed 134 }135 })136 }137 })138 }139 })140 })141 if ('close' in main) main.close()142 },143144 /**145 * Default reporter, outputting to the DOM.146 *147 * Options:148 * - reportToId id of element to output reports to, defaults to 'jspec'149 * - failuresOnly displays only suites with failing specs150 *151 * @api public152 */153154 DOM : function(results, options) {155 var id = option('reportToId') || 'jspec',156 report = document.getElementById(id),157 failuresOnly = option('failuresOnly'),158 classes = results.stats.failures ? 'has-failures' : ''159 if (!report) throw 'JSpec requires the element #' + id + ' to output its reports'160 161 function bodyContents(body) {162 return JSpec.163 escape(JSpec.contentsOf(body)).164 replace(/^ */gm, function(a){ return (new Array(Math.round(a.length / 3))).join(' ') }).165 replace(/\r\n|\r|\n/gm, '<br/>')166 }167 168 report.innerHTML = '<div id="jspec-report" class="' + classes + '"><div class="heading"> \169 <span class="passes">Passes: <em>' + results.stats.passes + '</em></span> \170 <span class="failures">Failures: <em>' + results.stats.failures + '</em></span> \171 <span class="passes">Duration: <em>' + results.duration + '</em> ms</span> \172 </div><table class="suites">' + map(results.allSuites, function(suite) {173 var displaySuite = failuresOnly ? suite.ran && !suite.passed() : suite.ran174 if (displaySuite && suite.isExecutable())175 return '<tr class="description"><td colspan="2">' + escape(suite.description) + '</td></tr>' +176 map(suite.specs, function(i, spec) {177 return '<tr class="' + (i % 2 ? 'odd' : 'even') + '">' +178 (spec.requiresImplementation() ?179 '<td class="requires-implementation" colspan="2">' + escape(spec.description) + '</td>' :180 (spec.passed() && !failuresOnly) ?181 '<td class="pass">' + escape(spec.description)+ '</td><td>' + spec.assertionsGraph() + '</td>' :182 !spec.passed() ?183 '<td class="fail">' + escape(spec.description) + 184 map(spec.failures(), function(a){ return '<em>' + escape(a.message) + '</em>' }).join('') +185 '</td><td>' + spec.assertionsGraph() + '</td>' :186 '') +187 '<tr class="body"><td colspan="2"><pre>' + bodyContents(spec.body) + '</pre></td></tr>'188 }).join('') + '</tr>'189 }).join('') + '</table></div>'190 },191 192 /**193 * Terminal reporter.194 *195 * @api public196 */197 198 Terminal : function(results, options) {199 var failuresOnly = option('failuresOnly')200 print(color("\n Passes: ", 'bold') + color(results.stats.passes, 'green') + 201 color(" Failures: ", 'bold') + color(results.stats.failures, 'red') +202 color(" Duration: ", 'bold') + color(results.duration, 'green') + " ms \n")203 204 function indent(string) {205 return string.replace(/^(.)/gm, ' $1')206 }207 208 each(results.allSuites, function(suite) {209 var displaySuite = failuresOnly ? suite.ran && !suite.passed() : suite.ran210 if (displaySuite && suite.isExecutable()) {211 print(color(' ' + suite.description, 'bold'))212 each(suite.specs, function(spec){213 var assertionsGraph = inject(spec.assertions, '', function(graph, assertion){214 return graph + color('.', assertion.passed ? 'green' : 'red')215 })216 if (spec.requiresImplementation())217 print(color(' ' + spec.description, 'blue') + assertionsGraph)218 else if (spec.passed() && !failuresOnly)219 print(color(' ' + spec.description, 'green') + assertionsGraph)220 else if (!spec.passed())221 print(color(' ' + spec.description, 'red') + assertionsGraph + 222 "\n" + indent(map(spec.failures(), function(a){ return a.message }).join("\n")) + "\n")223 })224 print("")225 }226 })227 228 quit(results.stats.failures)229 }230 },231 232 Assertion : function(matcher, actual, expected, negate) {233 extend(this, {234 message: '',235 passed: false,236 actual: actual,237 negate: negate,238 matcher: matcher,239 expected: expected,240 241 // Report assertion results242 243 report : function() {244 if (JSpec.assert) 245 this.passed ? JSpec.stats.passes++ : JSpec.stats.failures++246 return this247 },248 249 // Run the assertion250 251 run : function() {252 // TODO: remove unshifting 253 expected.unshift(actual)254 this.result = matcher.match.apply(this, expected)255 this.passed = negate ? !this.result : this.result256 if (!this.passed) this.message = matcher.message.call(this, actual, expected, negate, matcher.name)257 return this258 }259 })260 },261 262 ProxyAssertion : function(object, method, times, negate) {263 var self = this,264 old = object[method]265 266 // Proxy267 268 object[method] = function(){269 var args = toArray(arguments),270 result = old.apply(object, args)271 self.calls.push({ args : args, result : result })272 return result273 }274 275 // Times276 277 this.times = {278 once : 1,279 twice : 2280 }[times] || times || 1281 282 extend(this, {283 calls: [],284 message: '',285 defer: true,286 passed: false,287 negate: negate,288 object: object,289 method: method,290 291 // Proxy return value292 293 and_return : function(result) {294 this.expectedResult = result295 return this296 },297 298 // Proxy arguments passed299 300 with_args : function() {301 this.expectedArgs = toArray(arguments)302 return this303 },304 305 // Check if any calls have failing results306 307 anyResultsFail : function() {308 return any(this.calls, function(call){309 return self.expectedResult.an_instance_of ?310 call.result.constructor != self.expectedResult.an_instance_of:311 !equal(self.expectedResult, call.result)312 })313 },314 315 // Check if any calls have passing results316 317 anyResultsPass : function() {318 return any(this.calls, function(call){319 return self.expectedResult.an_instance_of ?320 call.result.constructor == self.expectedResult.an_instance_of:321 equal(self.expectedResult, call.result)322 })323 },324 325 // Return the passing result326 327 passingResult : function() {328 return this.anyResultsPass().result329 },330331 // Return the failing result332 333 failingResult : function() {334 return this.anyResultsFail().result335 },336 337 // Check if any arguments fail338 339 anyArgsFail : function() {340 return any(this.calls, function(call){341 return any(self.expectedArgs, function(i, arg){342 if (arg == null) return call.args[i] == null343 return arg.an_instance_of ?344 call.args[i].constructor != arg.an_instance_of:345 !equal(arg, call.args[i])346 347 })348 })349 },350 351 // Check if any arguments pass352 353 anyArgsPass : function() {354 return any(this.calls, function(call){355 return any(self.expectedArgs, function(i, arg){356 return arg.an_instance_of ?357 call.args[i].constructor == arg.an_instance_of:358 equal(arg, call.args[i])359 360 })361 })362 },363 364 // Return the passing args365 366 passingArgs : function() {367 return this.anyArgsPass().args368 },369 370 // Return the failing args371 372 failingArgs : function() {373 return this.anyArgsFail().args374 },375 376 // Report assertion results377 378 report : function() {379 if (JSpec.assert) 380 this.passed ? ++JSpec.stats.passes : ++JSpec.stats.failures381 return this382 },383 384 // Run the assertion385 386 run : function() {387 var methodString = 'expected ' + object.toString() + '.' + method + '()' + (negate ? ' not' : '' )388 389 function times(n) {390 return n > 2 ? n + ' times' : { 1: 'once', 2: 'twice' }[n]391 }392 393 if (this.expectedResult != null && (negate ? this.anyResultsPass() : this.anyResultsFail()))394 this.message = methodString + ' to return ' + puts(this.expectedResult) + 395 ' but ' + (negate ? 'it did' : 'got ' + puts(this.failingResult())) 396397 if (this.expectedArgs && (negate ? !this.expectedResult && this.anyArgsPass() : this.anyArgsFail()))398 this.message = methodString + ' to be called with ' + puts.apply(this, this.expectedArgs) +399 ' but was' + (negate ? '' : ' called with ' + puts.apply(this, this.failingArgs()))400401 if (negate ? !this.expectedResult && !this.expectedArgs && this.calls.length >= this.times : this.calls.length != this.times)402 this.message = methodString + ' to be called ' + times(this.times) + 403 ', but ' + (this.calls.length == 0 ? ' was not called' : ' was called ' + times(this.calls.length))404 405 if (!this.message.length) 406 this.passed = true407 408 return this409 }410 })411 },412 413 /**414 * Specification Suite block object.415 *416 * @param {string} description417 * @param {function} body418 * @api private419 */420421 Suite : function(description, body, isShared) {422 var self = this423 extend(this, {424 body: body,425 description: description,426 suites: [],427 sharedBehaviors: [],428 specs: [],429 ran: false,430 shared: isShared, 431 hooks: { 'before' : [], 'after' : [], 432 'before_each' : [], 'after_each' : [],433 'before_nested' : [], 'after_nested' : []},434 435 // Add a spec to the suite436437 addSpec : function(description, body) {438 var spec = new JSpec.Spec(description, body)439 this.specs.push(spec)440 JSpec.stats.specs++ // TODO: abstract441 spec.suite = this442 },443444 // Add a before hook to the suite445446 addBefore : function(options, body) {447 body.options = options || {}448 this.befores.push(body)449 },450451 // Add an after hook to the suite452453 addAfter : function(options, body) {454 body.options = options || {}455 this.afters.unshift(body)456 },457458 // Add a hook to the suite459 460 addHook : function(hook, body) {461 this.hooks[hook].push(body)462 },463464 // Add a nested suite465466 addSuite : function(description, body, isShared) {467 var suite = new JSpec.Suite(description, body, isShared)468 JSpec.allSuites.push(suite)469 suite.name = suite.description470 suite.description = this.description + ' ' + suite.description471 this.suites.push(suite)472 suite.suite = this473 },474475 // Invoke a hook in context to this suite476477 hook : function(hook) {478 if (hook != 'before' && hook != 'after') 479 if (this.suite) this.suite.hook(hook)480481 each(this.hooks[hook], function(body) {482 JSpec.evalBody(body, "Error in hook '" + hook + "', suite '" + self.description + "': ")483 })484 },485 486 // Check if nested suites are present487488 hasSuites : function() {489 return this.suites.length 490 },491492 // Check if this suite has specs493494 hasSpecs : function() {495 return this.specs.length496 },497498 // Check if the entire suite passed499500 passed : function() {501 return !any(this.specs, function(spec){502 return !spec.passed() 503 })504 },505506 isShared : function(){507 return this.shared508 },509510 isExecutable : function() {511 return !this.isShared() && this.hasSpecs()512 }513 })514 },515 516 /**517 * Specification block object.518 *519 * @param {string} description520 * @param {function} body521 * @api private522 */523524 Spec : function(description, body) {525 extend(this, {526 body: body,527 description: description,528 assertions: [],529 530 // Add passing assertion531 532 pass : function(message) {533 this.assertions.push({ passed: true, message: message })534 if (JSpec.assert) ++JSpec.stats.passes535 },536 537 // Add failing assertion538 539 fail : function(message) {540 this.assertions.push({ passed: false, message: message })541 if (JSpec.assert) ++JSpec.stats.failures542 },543 544 // Run deferred assertions545 546 runDeferredAssertions : function() {547 each(this.assertions, function(assertion){548 if (assertion.defer) assertion.run().report(), hook('afterAssertion', assertion)549 })550 },551 552 // Find first failing assertion553554 failure : function() {555 return find(this.assertions, function(assertion){556 return !assertion.passed557 })558 },559560 // Find all failing assertions561562 failures : function() {563 return select(this.assertions, function(assertion){564 return !assertion.passed565 })566 },567568 // Weither or not the spec passed569570 passed : function() {571 return !this.failure()572 },573574 // Weither or not the spec requires implementation (no assertions)575576 requiresImplementation : function() {577 return this.assertions.length == 0578 },579580 // Sprite based assertions graph581582 assertionsGraph : function() {583 return map(this.assertions, function(assertion){584 return '<span class="assertion ' + (assertion.passed ? 'passed' : 'failed') + '"></span>'585 }).join('')586 }587 })588 },589 590 Module : function(methods) {591 extend(this, methods)592 },593 594 JSON : {595 596 /**597 * Generic sequences.598 */599 600 meta : {601 '\b' : '\\b',602 '\t' : '\\t',603 '\n' : '\\n',604 '\f' : '\\f',605 '\r' : '\\r',606 '"' : '\\"',607 '\\' : '\\\\'608 },609 610 /**611 * Escapable sequences.612 */613 614 escapable : /[\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,615 616 /**617 * JSON encode _object_.618 *619 * @param {mixed} object620 * @return {string}621 * @api private622 */623 624 encode : function(object) {625 var self = this626 if (object == undefined || object == null) return 'null'627 if (object === true) return 'true'628 if (object === false) return 'false'629 switch (typeof object) {630 case 'number': return object631 case 'string': return this.escapable.test(object) ?632 '"' + object.replace(this.escapable, function (a) {633 return typeof self.meta[a] === 'string' ? self.meta[a] :634 '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4)635 }) + '"' :636 '"' + object + '"'637 case 'object': 638 if (object.constructor == Array)639 return '[' + map(object, function(val){640 return self.encode(val)641 }).join(', ') + ']'642 else if (object)643 return '{' + map(object, function(key, val){644 return self.encode(key) + ':' + self.encode(val)645 }).join(', ') + '}'646 }647 return 'null'648 }649 },650 651 // --- DSLs652 653 DSLs : {654 snake : {655 expect : function(actual){656 return JSpec.expect(actual)657 },658659 describe : function(description, body) {660 return JSpec.currentSuite.addSuite(description, body, false)661 },662663 it : function(description, body) {664 return JSpec.currentSuite.addSpec(description, body)665 },666667 before : function(body) {668 return JSpec.currentSuite.addHook('before', body)669 },670 671 after : function(body) {672 return JSpec.currentSuite.addHook('after', body)673 },674 675 before_each : function(body) {676 return JSpec.currentSuite.addHook('before_each', body)677 },678 679 after_each : function(body) {680 return JSpec.currentSuite.addHook('after_each', body)681 },682683 before_nested : function(body) {684 return JSpec.currentSuite.addHook('before_nested', body)685 },686 687 after_nested : function(body){688 return JSpec.currentSuite.addhook('after_nested', body)689 },690 691 shared_behaviors_for : function(description, body){692 return JSpec.currentSuite.addSuite(description, body, true)693 },694695 should_behave_like : function(description) {696 return JSpec.shareBehaviorsOf(description)697 }698 }699 },700701 // --- Methods702 703 /**704 * Check if _value_ is 'stop'. For use as a705 * utility callback function.706 *707 * @param {mixed} value708 * @return {bool}709 * @api public710 */711 712 haveStopped : function(value) {713 return value === 'stop'714 },715 716 /**717 * Include _object_ which may be a hash or Module instance.718 *719 * @param {hash, Module} object720 * @return {JSpec}721 * @api public722 */723 724 include : function(object) {725 var module = object.constructor == JSpec.Module ? object : new JSpec.Module(object)726 this.modules.push(module)727 if ('init' in module) module.init()728 if ('utilities' in module) extend(this.defaultContext, module.utilities)729 if ('matchers' in module) this.addMatchers(module.matchers)730 if ('reporters' in module) extend(this.reporters, module.reporters)731 if ('DSLs' in module)732 each(module.DSLs, function(name, methods){733 JSpec.DSLs[name] = JSpec.DSLs[name] || {}734 extend(JSpec.DSLs[name], methods)735 })736 return this737 },738 739 /**740 * Add a module hook _name_, which is immediately741 * called per module with the _args_ given. An array of742 * hook return values is returned.743 *744 * @param {name} string745 * @param {...} args746 * @return {array}747 * @api private748 */749 750 hook : function(name, args) {751 args = toArray(arguments, 1)752 return inject(JSpec.modules, [], function(results, module){753 if (typeof module[name] == 'function')754 results.push(JSpec.evalHook(module, name, args))755 })756 },757 758 /**759 * Eval _module_ hook _name_ with _args_. Evaluates in context760 * to the module itself, JSpec, and JSpec.context.761 *762 * @param {Module} module763 * @param {string} name764 * @param {array} args765 * @return {mixed}766 * @api private767 */768 769 evalHook : function(module, name, args) {770 hook('evaluatingHookBody', module, name)771 return module[name].apply(module, args)772 },773 774 /**775 * Same as hook() however accepts only one _arg_ which is776 * considered immutable. This function passes the arg777 * to the first module, then passes the return value of the last778 * module called, to the following module. 779 *780 * @param {string} name781 * @param {mixed} arg782 * @return {mixed}783 * @api private784 */785 786 hookImmutable : function(name, arg) {787 return inject(JSpec.modules, arg, function(result, module){788 if (typeof module[name] == 'function')789 return JSpec.evalHook(module, name, [result])790 })791 },792 793 /**794 * Find a shared example suite by its description or name.795 * First searches parent tree of suites for shared behavior796 * before falling back to global scoped nested behaviors.797 *798 * @param {string} description799 * @return {Suite}800 * @api private801 */802 803 findSharedBehavior : function(description) {804 var behavior805 return (behavior = JSpec.findLocalSharedBehavior(description))806 ? behavior807 : JSpec.findGlobalSharedBehavior(description)808 },809810 /**811 * Find a shared example suite within the current suite's812 * parent tree by its description or name.813 *814 * @param {string} description815 * @return {Suite}816 * @api private817 */818 819 findLocalSharedBehavior : function(description) {820 var behavior,821 currentSuite = JSpec.currentSuite.suite822 while (currentSuite)823 if (behavior = find(currentSuite.suites, JSpec.suiteDescriptionPredicate(description)))824 return behavior825 else826 currentSuite = currentSuite.suite827 },828 829 /**830 * Find a shared example suite within the global831 * scope by its description or name.832 *833 * @param {string} description834 * @return {Suite}835 * @api private836 */837 838 findGlobalSharedBehavior : function(description) {839 return find(JSpec.suites, JSpec.suiteDescriptionPredicate(description))840 },841 842 /**843 * Build a predicate that will match a suite based on name or description844 *845 * @param {string} description846 * @return {function}847 * @api private848 */849 850 suiteDescriptionPredicate : function(description) {851 return function(suite){852 return suite.name === description ||853 suite.description === description854 }855 },856857 /**858 * Share behaviors (specs) of the given suite with859 * the current suite.860 *861 * @param {string} description862 * @api public863 */864 865 shareBehaviorsOf : function(description) {866 var suite = JSpec.findSharedBehavior(description)867 if (suite)868 JSpec.evalBody(suite.body)869 else870 throw new Error("failed to find shared behaviors named `" + description + "'")871 },872 873 874 /**875 * Convert arguments to an array.876 *877 * @param {object} arguments878 * @param {int} offset879 * @return {array}880 * @api public881 */882 883 toArray : function(arguments, offset) {884 return Array.prototype.slice.call(arguments, offset || 0)885 },886 887 /**888 * Return ANSI-escaped colored string.889 *890 * @param {string} string891 * @param {string} color892 * @return {string}893 * @api public894 */895 896 color : function(string, color) {897 if (option('disableColors')) {898 return string899 } else {900 return "\u001B[" + {901 bold : 1,902 black : 30,903 red : 31,904 green : 32,905 yellow : 33,906 blue : 34,907 magenta : 35,908 cyan : 36,909 white : 37910 }[color] + 'm' + string + "\u001B[0m"911 }912 },913 914 /**915 * Default matcher message callback.916 *917 * @api private918 */919 920 defaultMatcherMessage : function(actual, expected, negate, name) {921 return 'expected ' + puts(actual) + ' to ' + 922 (negate ? 'not ' : '') + 923 name.replace(/_/g, ' ') +924 ' ' + (expected.length > 1 ?925 puts.apply(this, expected.slice(1)) :926 '')927 },928 929 /**930 * Normalize a matcher message.931 *932 * When no messge callback is present the defaultMatcherMessage933 * will be assigned, will suffice for most matchers.934 *935 * @param {hash} matcher936 * @return {hash}937 * @api public938 */939 940 normalizeMatcherMessage : function(matcher) {941 if (typeof matcher.message != 'function') 942 matcher.message = this.defaultMatcherMessage943 return matcher944 },945 946 /**947 * Normalize a matcher body948 * 949 * This process allows the following conversions until950 * the matcher is in its final normalized hash state.951 *952 * - '==' becomes 'actual == expected'953 * - 'actual == expected' becomes 'return actual == expected'954 * - function(actual, expected) { return actual == expected } becomes 955 * { match : function(actual, expected) { return actual == expected }}956 *957 * @param {mixed} body958 * @return {hash}959 * @api public960 */961 962 normalizeMatcherBody : function(body) {963 var captures964 switch (body.constructor) {965 case String:966 if (captures = body.match(/^alias (\w+)/)) return JSpec.matchers[last(captures)]967 if (body.length < 4) body = 'actual ' + body + ' expected'968 return { match: function(actual, expected) { return eval(body) }} 969 970 case Function:971 return { match: body }972 973 default:974 return body975 }976 },977 978 /**979 * Get option value. This method first checks if980 * the option key has been set via the query string,981 * otherwise returning the options hash value.982 *983 * @param {string} key984 * @return {mixed}985 * @api public986 */987 988 option : function(key) {989 return (value = query(key)) !== null ? value :990 JSpec.options[key] || null991 },992 993 /**994 * Check if object _a_, is equal to object _b_.995 *996 * @param {object} a997 * @param {object} b998 * @return {bool}999 * @api private1000 */1001 1002 equal: function(a, b) {1003 if (typeof a != typeof b) return1004 if (a === b) return true1005 if (a instanceof RegExp)1006 return a.toString() === b.toString()1007 if (a instanceof Date)1008 return Number(a) === Number(b)1009 if (typeof a != 'object') return1010 if (a.length !== undefined)1011 if (a.length !== b.length) return1012 else1013 for (var i = 0, len = a.length; i < len; ++i)1014 if (!equal(a[i], b[i]))1015 return1016 for (var key in a)1017 if (!equal(a[key], b[key]))1018 return1019 return true1020 },10211022 /**1023 * Return last element of an array.1024 *1025 * @param {array} array1026 * @return {object}1027 * @api public1028 */10291030 last : function(array) {1031 return array[array.length - 1]1032 },10331034 /**1035 * Convert object(s) to a print-friend string.1036 *1037 * @param {...} object1038 * @return {string}1039 * @api public1040 */10411042 puts : function(object) {1043 if (arguments.length > 1)1044 return map(toArray(arguments), function(arg){1045 return puts(arg)1046 }).join(', ')1047 if (object === undefined) return 'undefined'1048 if (object === null) return 'null'1049 if (object === true) return 'true'1050 if (object === false) return 'false'1051 if (object.an_instance_of) return 'an instance of ' + object.an_instance_of.name1052 if (object.jquery && object.selector.length > 0) return 'selector ' + puts(object.selector)1053 if (object.jquery) return object.get(0).outerHTML1054 if (object.nodeName) return object.outerHTML1055 switch (object.constructor) {1056 case Function: return object.name || object 1057 case String: 1058 return '"' + object1059 .replace(/"/g, '\\"')1060 .replace(/\n/g, '\\n')1061 .replace(/\t/g, '\\t')1062 + '"'1063 case Array: 1064 return inject(object, '[', function(b, v){1065 return b + ', ' + puts(v)1066 }).replace('[,', '[') + ' ]'1067 case Object:1068 object.__hit__ = true1069 return inject(object, '{', function(b, k, v) {1070 if (k == '__hit__') return b1071 return b + ', ' + k + ': ' + (v && v.__hit__ ? '<circular reference>' : puts(v))1072 }).replace('{,', '{') + ' }'1073 default: 1074 return object.toString()1075 }1076 },10771078 /**1079 * Parse an XML String and return a 'document'.1080 *1081 * @param {string} text1082 * @return {document}1083 * @api public1084 */10851086 parseXML : function(text) {1087 var xmlDoc1088 if (window.DOMParser)1089 xmlDoc = (new DOMParser()).parseFromString(text, "text/xml")1090 else {1091 xmlDoc = new ActiveXObject("Microsoft.XMLDOM")1092 xmlDoc.async = "false"1093 xmlDoc.loadXML(text)1094 }1095 return xmlDoc1096 },10971098 /**1099 * Escape HTML.1100 *1101 * @param {string} html1102 * @return {string}1103 * @api public1104 */11051106 escape : function(html) {1107 return html.toString()1108 .replace(/&/gmi, '&amp;')1109 .replace(/"/gmi, '&quot;')1110 .replace(/>/gmi, '&gt;')1111 .replace(/</gmi, '&lt;')1112 },1113 1114 /**1115 * Perform an assertion without reporting.1116 *1117 * This method is primarily used for internal1118 * matchers in order retain DRYness. May be invoked 1119 * like below:1120 *1121 * does('foo', 'eql', 'foo')1122 * does([1,2], 'include', 1, 2)1123 *1124 * External hooks are not run for internal assertions1125 * performed by does().1126 *1127 * @param {mixed} actual1128 * @param {string} matcher1129 * @param {...} expected1130 * @return {mixed}1131 * @api private1132 */1133 1134 does : function(actual, matcher, expected) {1135 var assertion = new JSpec.Assertion(JSpec.matchers[matcher], actual, toArray(arguments, 2))1136 return assertion.run().result1137 },11381139 /**1140 * Perform an assertion.1141 *1142 * expect(true).to('be', true)1143 * expect('foo').not_to('include', 'bar')1144 * expect([1, [2]]).to('include', 1, [2])1145 *1146 * @param {mixed} actual1147 * @return {hash}1148 * @api public1149 */11501151 expect : function(actual) {1152 function assert(matcher, args, negate) {1153 var expected = toArray(args, 1)1154 matcher.negate = negate 1155 var assertion = new JSpec.Assertion(matcher, actual, expected, negate)1156 hook('beforeAssertion', assertion)1157 if (matcher.defer) assertion.run()1158 else JSpec.currentSpec.assertions.push(assertion.run().report()), hook('afterAssertion', assertion)1159 return assertion.result1160 }1161 1162 function to(matcher) {1163 return assert(matcher, arguments, false)1164 }1165 1166 function not_to(matcher) {1167 return assert(matcher, arguments, true)1168 }1169 1170 return {1171 to : to,1172 should : to,1173 not_to: not_to,1174 should_not : not_to1175 }1176 },11771178 /**1179 * Strim whitespace or chars.1180 *1181 * @param {string} string1182 * @param {string} chars1183 * @return {string}1184 * @api public1185 */11861187 strip : function(string, chars) {1188 return string.1189 replace(new RegExp('[' + (chars || '\\s') + ']*$'), '').1190 replace(new RegExp('^[' + (chars || '\\s') + ']*'), '')1191 },1192 1193 /**1194 * Call an iterator callback with arguments a, or b1195 * depending on the arity of the callback.1196 *1197 * @param {function} callback1198 * @param {mixed} a1199 * @param {mixed} b1200 * @return {mixed}1201 * @api private1202 */1203 1204 callIterator : function(callback, a, b) {1205 return callback.length == 1 ? callback(b) : callback(a, b)1206 },1207 1208 /**1209 * Extend an object with another.1210 *1211 * @param {object} object1212 * @param {object} other1213 * @api public1214 */1215 1216 extend : function(object, other) {1217 each(other, function(property, value){1218 object[property] = value1219 })1220 },1221 1222 /**1223 * Iterate an object, invoking the given callback.1224 *1225 * @param {hash, array} object1226 * @param {function} callback1227 * @return {JSpec}1228 * @api public1229 */12301231 each : function(object, callback) {1232 if (object.constructor == Array)1233 for (var i = 0, len = object.length; i < len; ++i)1234 callIterator(callback, i, object[i])1235 else1236 for (var key in object) 1237 if (object.hasOwnProperty(key))1238 callIterator(callback, key, object[key])1239 },12401241 /**1242 * Iterate with memo.1243 *1244 * @param {hash, array} object1245 * @param {object} memo1246 * @param {function} callback1247 * @return {object}1248 * @api public1249 */12501251 inject : function(object, memo, callback) {1252 each(object, function(key, value){1253 memo = (callback.length == 2 ?1254 callback(memo, value):1255 callback(memo, key, value)) ||1256 memo1257 })1258 return memo1259 },1260 1261 /**1262 * Destub _object_'s _method_. When no _method_ is passed1263 * all stubbed methods are destubbed. When no arguments1264 * are passed every object found in JSpec.stubbed will be1265 * destubbed.1266 *1267 * @param {mixed} object1268 * @param {string} method1269 * @api public1270 */1271 1272 destub : function(object, method) {1273 var captures1274 if (method) {1275 if (object['__prototype__' + method])1276 delete object[method]1277 else1278 object[method] = object['__original__' + method]1279 delete object['__prototype__' + method]1280 delete object['__original____' + method]1281 }1282 else if (object) {1283 for (var key in object)1284 if (captures = key.match(/^(?:__prototype__|__original__)(.*)/))1285 destub(object, captures[1])1286 }1287 else1288 while (JSpec.stubbed.length)1289 destub(JSpec.stubbed.shift())1290 },1291 1292 /**1293 * Stub _object_'s _method_. 1294 *1295 * stub(foo, 'toString').and_return('bar')1296 *1297 * @param {mixed} object1298 * @param {string} method1299 * @return {hash}1300 * @api public1301 */1302 1303 stub : function(object, method) {1304 hook('stubbing', object, method)1305 JSpec.stubbed.push(object)1306 var type = object.hasOwnProperty(method) ? '__original__' : '__prototype__'1307 object[type + method] = object[method]1308 object[method] = function(){}1309 return {1310 and_return : function(value) {1311 if (typeof value == 'function') object[method] = value1312 else object[method] = function(){ return value }1313 }1314 }1315 },1316 1317 /**1318 * Map callback return values.1319 *1320 * @param {hash, array} object1321 * @param {function} callback1322 * @return {array}1323 * @api public1324 */13251326 map : function(object, callback) {1327 return inject(object, [], function(memo, key, value){1328 memo.push(callIterator(callback, key, value))1329 })1330 },1331 1332 /**1333 * Returns the first matching expression or null.1334 *1335 * @param {hash, array} object1336 * @param {function} callback1337 * @return {mixed}1338 * @api public1339 */1340 1341 any : function(object, callback) {1342 return inject(object, null, function(state, key, value){1343 if (state == undefined)1344 return callIterator(callback, key, value) ? value : state1345 })1346 },1347 1348 /**1349 * Returns an array of values collected when the callback1350 * given evaluates to true.1351 *1352 * @param {hash, array} object1353 * @return {function} callback1354 * @return {array}1355 * @api public1356 */1357 1358 select : function(object, callback) {1359 return inject(object, [], function(selected, key, value){1360 if (callIterator(callback, key, value))1361 selected.push(value)1362 })1363 },13641365 /**1366 * Define matchers.1367 *1368 * @param {hash} matchers1369 * @api public1370 */13711372 addMatchers : function(matchers) {1373 each(matchers, function(name, body){1374 JSpec.addMatcher(name, body) 1375 })1376 },1377 1378 /**1379 * Define a matcher.1380 *1381 * @param {string} name1382 * @param {hash, function, string} body1383 * @api public1384 */1385 1386 addMatcher : function(name, body) {1387 hook('addingMatcher', name, body)1388 if (name.indexOf(' ') != -1) {1389 var matchers = name.split(/\s+/)1390 var prefix = matchers.shift()1391 each(matchers, function(name) {1392 JSpec.addMatcher(prefix + '_' + name, body(name))1393 })1394 }1395 this.matchers[name] = this.normalizeMatcherMessage(this.normalizeMatcherBody(body))1396 this.matchers[name].name = name1397 },1398 1399 /**1400 * Add a root suite to JSpec.1401 *1402 * @param {string} description1403 * @param {body} function1404 * @api public1405 */1406 1407 describe : function(description, body) {1408 var suite = new JSpec.Suite(description, body, false)1409 hook('addingSuite', suite)1410 this.allSuites.push(suite)1411 this.suites.push(suite)1412 },1413 1414 /**1415 * Add a shared example suite to JSpec.1416 *1417 * @param {string} description1418 * @param {body} function1419 * @api public1420 */1421 1422 shared_behaviors_for : function(description, body) {1423 var suite = new JSpec.Suite(description, body, true)1424 hook('addingSuite', suite)1425 this.allSuites.push(suite)1426 this.suites.push(suite)1427 },14281429 /**1430 * Return the contents of a function body.1431 *1432 * @param {function} body1433 * @return {string}1434 * @api public1435 */1436 1437 contentsOf : function(body) {1438 return body.toString().match(/^[^\{]*{((.*\n*)*)}/m)[1]1439 },14401441 /**1442 * Evaluate a JSpec capture body.1443 *1444 * @param {function} body1445 * @param {string} errorMessage (optional)1446 * @return {Type}1447 * @api private1448 */14491450 evalBody : function(body, errorMessage) {1451 var dsl = this.DSL || this.DSLs.snake1452 var matchers = this.matchers1453 var context = this.context || this.defaultContext1454 var contents = this.contentsOf(body)1455 hook('evaluatingBody', dsl, matchers, context, contents)1456 with (dsl){ with (context) { with (matchers) { eval(contents) }}}1457 },14581459 /**1460 * Pre-process a string of JSpec.1461 *1462 * @param {string} input1463 * @return {string}1464 * @api private1465 */14661467 preprocess : function(input) {1468 if (typeof input != 'string') return1469 input = hookImmutable('preprocessing', input)1470 return input.1471 replace(/\t/g, ' ').1472 replace(/\r\n|\n|\r/g, '\n').1473 split('__END__')[0].1474 replace(/([\w\.]+)\.(stub|destub)\((.*?)\)$/gm, '$2($1, $3)').1475 replace(/describe\s+(.*?)$/gm, 'describe($1, function(){').1476 replace(/shared_behaviors_for\s+(.*?)$/gm, 'shared_behaviors_for($1, function(){').1477 replace(/^\s+it\s+(.*?)$/gm, ' it($1, function(){').1478 replace(/^ *(before_nested|after_nested|before_each|after_each|before|after)(?= |\n|$)/gm, 'JSpec.currentSuite.addHook("$1", function(){').1479 replace(/^\s*end(?=\s|$)/gm, '});').1480 replace(/-\{/g, 'function(){').1481 replace(/(\d+)\.\.(\d+)/g, function(_, a, b){ return range(a, b) }).1482 replace(/\.should([_\.]not)?[_\.](\w+)(?: |;|$)(.*)$/gm, '.should$1_$2($3)').1483 replace(/([\/\s]*)(.+?)\.(should(?:[_\.]not)?)[_\.](\w+)\((.*)\)\s*;?$/gm, '$1 expect($2).$3($4, $5)').1484 replace(/, \)/g, ')').1485 replace(/should\.not/g, 'should_not')1486 },14871488 /**1489 * Create a range string which can be evaluated to a native array.1490 *1491 * @param {int} start1492 * @param {int} end1493 * @return {string}1494 * @api public1495 */14961497 range : function(start, end) {1498 var current = parseInt(start), end = parseInt(end), values = [current]1499 if (end > current) while (++current <= end) values.push(current)1500 else while (--current >= end) values.push(current)1501 return '[' + values + ']'1502 },15031504 /**1505 * Report on the results. 1506 *1507 * @api public1508 */15091510 report : function() {1511 this.duration = Number(new Date) - this.start1512 hook('reporting', JSpec.options)1513 new (JSpec.options.reporter || JSpec.reporters.DOM)(JSpec, JSpec.options)1514 },15151516 /**1517 * Run the spec suites. Options are merged1518 * with JSpec options when present.1519 *1520 * @param {hash} options1521 * @return {JSpec}1522 * @api public1523 */15241525 run : function(options) {1526 if (any(hook('running'), haveStopped)) return this1527 if (options) extend(this.options, options)1528 this.start = Number(new Date)1529 each(this.suites, function(suite) { JSpec.runSuite(suite) })1530 return this1531 },1532 1533 /**1534 * Run a suite.1535 *1536 * @param {Suite} suite1537 * @api public1538 */15391540 runSuite : function(suite) {1541 if (!suite.isShared())1542 {1543 this.currentSuite = suite1544 this.evalBody(suite.body)1545 suite.ran = true1546 hook('beforeSuite', suite), suite.hook('before'), suite.hook('before_nested')1547 each(suite.specs, function(spec) {1548 hook('beforeSpec', spec)1549 suite.hook('before_each')1550 JSpec.runSpec(spec)1551 hook('afterSpec', spec)1552 suite.hook('after_each')1553 })1554 if (suite.hasSuites()) {1555 each(suite.suites, function(suite) {1556 JSpec.runSuite(suite)1557 })1558 }1559 hook('afterSuite', suite), suite.hook('after_nested'), suite.hook('after')1560 this.stats.suitesFinished++1561 } 1562 },1563 1564 /**1565 * Report a failure for the current spec.1566 *1567 * @param {string} message1568 * @api public1569 */1570 1571 fail : function(message) {1572 JSpec.currentSpec.fail(message)1573 },1574 1575 /**1576 * Report a passing assertion for the current spec.1577 *1578 * @param {string} message1579 * @api public1580 */1581 1582 pass : function(message) {1583 JSpec.currentSpec.pass(message)1584 },15851586 /**1587 * Run a spec.1588 *1589 * @param {Spec} spec1590 * @api public1591 */15921593 runSpec : function(spec) {1594 this.currentSpec = spec1595 try { this.evalBody(spec.body) }1596 catch (e) { fail(e) }1597 spec.runDeferredAssertions()1598 destub()1599 this.stats.specsFinished++1600 this.stats.assertions += spec.assertions.length1601 },16021603 /**1604 * Require a dependency, with optional message.1605 *1606 * @param {string} dependency1607 * @param {string} message (optional)1608 * @return {JSpec}1609 * @api public1610 */16111612 requires : function(dependency, message) {1613 hook('requiring', dependency, message)1614 try { eval(dependency) }1615 catch (e) { throw 'JSpec depends on ' + dependency + ' ' + message }1616 return this1617 },16181619 /**1620 * Query against the current query strings keys1621 * or the queryString specified.1622 *1623 * @param {string} key1624 * @param {string} queryString1625 * @return {string, null}1626 * @api private1627 */16281629 query : function(key, queryString) {1630 var queryString = (queryString || (main.location ? main.location.search : null) || '').substring(1)1631 return inject(queryString.split('&'), null, function(value, pair){1632 parts = pair.split('=')1633 return parts[0] == key ? parts[1].replace(/%20|\+/gmi, ' ') : value1634 })1635 },16361637 /**1638 * Ad-hoc POST request for JSpec server usage.1639 *1640 * @param {string} uri1641 * @param {string} data1642 * @api private1643 */1644 1645 post : function(uri, data) {1646 if (any(hook('posting', uri, data), haveStopped)) return1647 var request = this.xhr()1648 request.open('POST', uri, false)1649 request.setRequestHeader('Content-Type', 'application/json')1650 request.send(JSpec.JSON.encode(data))1651 },16521653 /**1654 * Instantiate an XMLHttpRequest.1655 *1656 * Here we utilize IE's lame ActiveXObjects first which1657 * allow IE access serve files via the file: protocol, otherwise1658 * we then default to XMLHttpRequest.1659 *1660 * @return {XMLHttpRequest, ActiveXObject}1661 * @api private1662 */1663 1664 xhr : function() {1665 return this.ieXhr() || new JSpec.request1666 },1667 1668 /**1669 * Return Microsoft piece of crap ActiveXObject.1670 *1671 * @return {ActiveXObject}1672 * @api public1673 */1674 1675 ieXhr : function() {1676 function object(str) {1677 try { return new ActiveXObject(str) } catch(e) {}1678 }1679 return object('Msxml2.XMLHTTP.6.0') ||1680 object('Msxml2.XMLHTTP.3.0') ||1681 object('Msxml2.XMLHTTP') ||1682 object('Microsoft.XMLHTTP')1683 },1684 1685 /**1686 * Check for HTTP request support.1687 *1688 * @return {bool}1689 * @api private1690 */1691 1692 hasXhr : function() {1693 return JSpec.request || 'ActiveXObject' in main1694 },1695 1696 /**1697 * Try loading _file_ returning the contents1698 * string or null. Chain to locate / read a file.1699 *1700 * @param {string} file1701 * @return {string}1702 * @api public1703 */1704 1705 tryLoading : function(file) {1706 try { return JSpec.load(file) } catch (e) {}1707 },17081709 /**1710 * Load a _file_'s contents.1711 *1712 * @param {string} file1713 * @param {function} callback1714 * @return {string}1715 * @api public1716 */17171718 load : function(file, callback) {1719 if (any(hook('loading', file), haveStopped)) return1720 if ('readFile' in main)1721 return readFile(file)1722 else if (this.hasXhr()) {1723 var request = this.xhr()1724 request.open('GET', file, false)1725 request.send(null)1726 if (request.readyState == 4 && 1727 (request.status == 0 || 1728 request.status.toString().charAt(0) == 2)) 1729 return request.responseText1730 }1731 else1732 throw new Error("failed to load `" + file + "'")1733 },17341735 /**1736 * Load, pre-process, and evaluate a file.1737 *1738 * @param {string} file1739 * @param {JSpec}1740 * @api public1741 */17421743 exec : function(file) {1744 if (any(hook('executing', file), haveStopped)) return this1745 eval('with (JSpec){' + this.preprocess(this.load(file)) + '}')1746 return this1747 }1748 }1749 1750 // --- Node.js support1751 1752 if (typeof GLOBAL === 'object' && typeof exports === 'object') {1753 var fs = require('fs')1754 quit = process.exit1755 print = require('sys').puts1756 readFile = function(file){1757 return fs.readFileSync(file).toString('utf8')1758 }1759 }1760 1761 // --- Utility functions17621763 var main = this,1764 find = JSpec.any,1765 utils = 'haveStopped stub hookImmutable hook destub map any last pass fail range each option inject select \1766 error escape extend puts query strip color does addMatchers callIterator toArray equal'.split(/\s+/)1767 while (utils.length) eval('var ' + utils[0] + ' = JSpec.' + utils.shift())1768 if (!main.setTimeout) main.setTimeout = function(callback){ callback() }17691770 // --- Matchers17711772 addMatchers({1773 equal : "===",1774 eql : "equal(actual, expected)",1775 be : "alias equal",1776 be_greater_than : ">",1777 be_less_than : "<",1778 be_at_least : ">=",1779 be_at_most : "<=",1780 be_a : "actual.constructor == expected",1781 be_an : "alias be_a",1782 be_an_instance_of : "actual instanceof expected",1783 be_null : "actual == null",1784 be_true : "actual == true",1785 be_false : "actual == false",1786 be_undefined : "typeof actual == 'undefined'",1787 be_type : "typeof actual == expected",1788 match : "typeof actual == 'string' ? actual.match(expected) : false",1789 respond_to : "typeof actual[expected] == 'function'",1790 have_length : "actual.length == expected",1791 be_within : "actual >= expected[0] && actual <= last(expected)",1792 have_length_within : "actual.length >= expected[0] && actual.length <= last(expected)",1793 1794 receive : { defer : true, match : function(actual, method, times) {1795 var proxy = new JSpec.ProxyAssertion(actual, method, times, this.negate)1796 JSpec.currentSpec.assertions.push(proxy)1797 return proxy1798 }},1799 1800 be_empty : function(actual) {1801 if (actual.constructor == Object && actual.length == undefined)1802 for (var key in actual)1803 return false;1804 return !actual.length1805 },18061807 include : function(actual) {1808 for (var state = true, i = 1; i < arguments.length; i++) {1809 var arg = arguments[i]1810 switch (actual.constructor) {1811 case String: 1812 case Number:1813 case RegExp:1814 case Function:1815 state = actual.toString().indexOf(arg) !== -11816 break1817 1818 case Object:1819 state = arg in actual1820 break1821 1822 case Array: 1823 state = any(actual, function(value){ return equal(value, arg) })1824 break1825 }1826 if (!state) return false1827 }1828 return true1829 },18301831 throw_error : { match : function(actual, expected, message) {1832 try { actual() }1833 catch (e) {1834 this.e = e1835 var assert = function(arg) {1836 switch (arg.constructor) {1837 case RegExp : return arg.test(e.message || e.toString())1838 case String : return arg == (e.message || e.toString())1839 case Function : return e instanceof arg || e.name == arg.name1840 }1841 }1842 return message ? assert(expected) && assert(message) :1843 expected ? assert(expected) :1844 true1845 }1846 }, message : function(actual, expected, negate) {1847 // TODO: refactor when actual is not in expected [0]1848 var message_for = function(i) {1849 if (expected[i] == undefined) return 'exception'1850 switch (expected[i].constructor) {1851 case RegExp : return 'exception matching ' + puts(expected[i])1852 case String : return 'exception of ' + puts(expected[i])1853 case Function : return expected[i].name || 'Error'1854 }1855 }1856 var exception = message_for(1) + (expected[2] ? ' and ' + message_for(2) : '')1857 return 'expected ' + exception + (negate ? ' not ' : '' ) +1858 ' to be thrown, but ' + (this.e ? 'got ' + puts(this.e) : 'nothing was')1859 }},1860 1861 have : function(actual, length, property) {1862 return actual[property] == null ? false : actual[property].length == length1863 },1864 1865 have_at_least : function(actual, length, property) {1866 return actual[property] == null ? (length === 0) : actual[property].length >= length1867 },1868 1869 have_at_most :function(actual, length, property) {1870 return actual[property] == null || actual[property].length <= length1871 },1872 1873 have_within : function(actual, range, property) {1874 var length = actual[property] == undefined ? 0 : actual[property].length1875 return length >= range.shift() && length <= range.pop()1876 },1877 1878 have_prop : function(actual, property, value) {1879 var actualVal = actual[property], actualType = typeof actualVal1880 return (actualType == 'function' || actualType == 'undefined') ? false :1881 typeof value === 'undefined' ||1882 does(actual[property],'eql',value)1883 },1884 1885 have_property : function(actual, property, value) {1886 var actualVal = actual[property], actualType = typeof actualVal1887 return (actualType == 'function' || actualType == 'undefined') ? false :1888 typeof value === 'undefined' ||1889 value === actualVal1890 }1891 })1892 1893})()
deleted:spec/lib/jspec.nodejs.js-18 removed
12// JSpec - node - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)34JSpec5.include({6 name: 'node',7 8 // --- Matchers9 10 matchers : {11 have_enumerable_property: 'actual.propertyIsEnumerable(expected)',12 have_writable_property: 'Object.getOwnPropertyDescriptor(actual, expected).writable === true',13 have_configurable_property: 'Object.getOwnPropertyDescriptor(actual, expected).configurable === true',14 have_keys: 'does(Object.keys(actual), "eql", expected)',15 have_prototype: 'Object.getPrototypeOf(actual) === expected'16 }17})18
deleted:spec/lib/jspec.shell.js-39 removed
12// JSpec - Shell - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)34;(function(){5 6 var _quit = quit7 8 Shell = {9 10 // --- Global11 12 main: this,13 14 // --- Commands15 16 commands: {17 quit: ['Terminate the shell', function(){ _quit() }],18 exit: ['Terminate the shell', function(){ _quit() }],19 p: ['Inspect an object', function(o){ return o.toSource() }]20 },21 22 /**23 * Start the interactive shell.24 *25 * @api public26 */27 28 start : function() {29 for (var name in this.commands)30 if (this.commands.hasOwnProperty(name))31 this.commands[name][1].length ?32 this.main[name] = this.commands[name][1] :33 this.main.__defineGetter__(name, this.commands[name][1])34 }35 }36 37 Shell.start()38 39})()
deleted:spec/lib/jspec.timers.js-90 removed
12// JSpec - Mock Timers - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)34;(function(){5 6 /**7 * Version.8 */9 10 mockTimersVersion = '1.0.2'11 12 /**13 * Localized timer stack.14 */15 16 var timers = []17 18 /**19 * Set mock timeout with _callback_ and timeout of _ms_.20 *21 * @param {function} callback22 * @param {int} ms23 * @return {int}24 * @api public25 */26 27 setTimeout = function(callback, ms) {28 var id29 return id = setInterval(function(){30 callback()31 clearInterval(id)32 }, ms)33 }34 35 /**36 * Set mock interval with _callback_ and interval of _ms_.37 *38 * @param {function} callback39 * @param {int} ms40 * @return {int}41 * @api public42 */4344 setInterval = function(callback, ms) {45 callback.step = ms, callback.current = callback.last = 046 return timers[timers.length] = callback, timers.length47 }48 49 /**50 * Destroy timer with _id_.51 *52 * @param {int} id53 * @return {bool}54 * @api public55 */5657 clearInterval = clearTimeout = function(id) {58 return delete timers[--id]59 }60 61 /**62 * Reset timers.63 *64 * @return {array}65 * @api public66 */67 68 resetTimers = function() {69 return timers = []70 }71 72 /**73 * Increment each timers internal clock by _ms_.74 *75 * @param {int} ms76 * @api public77 */78 79 tick = function(ms) {80 for (var i = 0, len = timers.length; i < len; ++i)81 if (timers[i] && (timers[i].current += ms))82 if (timers[i].current - timers[i].last >= timers[i].step) {83 var times = Math.floor((timers[i].current - timers[i].last) / timers[i].step)84 var remainder = (timers[i].current - timers[i].last) % timers[i].step85 timers[i].last = timers[i].current - remainder86 while (times-- && timers[i]) timers[i]()87 }88 }89 90})()
deleted:spec/lib/jspec.xhr.js-210 removed
12// JSpec - XHR - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)34(function(){56 var lastRequest78 // --- Original XMLHttpRequest910 var OriginalXMLHttpRequest = 'XMLHttpRequest' in this ?11 XMLHttpRequest :12 function(){}13 var OriginalActiveXObject = 'ActiveXObject' in this ?14 ActiveXObject :15 undefined1617 // --- MockXMLHttpRequest1819 var MockXMLHttpRequest = function() {20 this.requestHeaders = {}21 }2223 MockXMLHttpRequest.prototype = {24 status: 0,25 async: true,26 readyState: 0,27 responseXML: null,28 responseText: '',29 abort: function(){},30 onreadystatechange: function(){},3132 /**33 * Return response headers hash.34 */3536 getAllResponseHeaders : function(){37 return JSpec.inject(this.responseHeaders, '', function(buf, key, val){38 return buf + key + ': ' + val + '\r\n'39 })40 },4142 /**43 * Return case-insensitive value for header _name_.44 */4546 getResponseHeader : function(name) {47 return this.responseHeaders[name.toLowerCase()]48 },4950 /**51 * Set case-insensitive _value_ for header _name_.52 */5354 setRequestHeader : function(name, value) {55 this.requestHeaders[name.toLowerCase()] = value56 },5758 /**59 * Open mock request.60 */6162 open : function(method, url, async, user, password) {63 this.user = user64 this.password = password65 this.url = url66 this.readyState = 167 this.method = method.toUpperCase()68 if (async != undefined) this.async = async69 if (this.async) this.onreadystatechange()70 },7172 /**73 * Send request _data_.74 */7576 send : function(data) {77 var self = this78 this.data = data79 this.readyState = 480 if (this.method == 'HEAD') this.responseText = null81 this.responseHeaders['content-length'] = (this.responseText || '').length82 if(this.async) this.onreadystatechange()83 this.populateResponseXML()84 lastRequest = function(){85 return self86 }87 },8889 /**90 * Parse request body and populate responseXML if response-type is xml91 * Based on the standard specification : http://www.w3.org/TR/XMLHttpRequest/92 */93 populateResponseXML: function() {94 var type = this.getResponseHeader("content-type")95 if (!type || !this.responseText || !type.match(/(text\/xml|application\/xml|\+xml$)/g))96 return97 this.responseXML = JSpec.parseXML(this.responseText)98 }99 }100101 // --- Response status codes102103 JSpec.statusCodes = {104 100: 'Continue',105 101: 'Switching Protocols',106 200: 'OK',107 201: 'Created',108 202: 'Accepted',109 203: 'Non-Authoritative Information',110 204: 'No Content',111 205: 'Reset Content',112 206: 'Partial Content',113 300: 'Multiple Choice',114 301: 'Moved Permanently',115 302: 'Found',116 303: 'See Other',117 304: 'Not Modified',118 305: 'Use Proxy',119 307: 'Temporary Redirect',120 400: 'Bad Request',121 401: 'Unauthorized',122 402: 'Payment Required',123 403: 'Forbidden',124 404: 'Not Found',125 405: 'Method Not Allowed',126 406: 'Not Acceptable',127 407: 'Proxy Authentication Required',128 408: 'Request Timeout',129 409: 'Conflict',130 410: 'Gone',131 411: 'Length Required',132 412: 'Precondition Failed',133 413: 'Request Entity Too Large',134 414: 'Request-URI Too Long',135 415: 'Unsupported Media Type',136 416: 'Requested Range Not Satisfiable',137 417: 'Expectation Failed',138 422: 'Unprocessable Entity',139 500: 'Internal Server Error',140 501: 'Not Implemented',141 502: 'Bad Gateway',142 503: 'Service Unavailable',143 504: 'Gateway Timeout',144 505: 'HTTP Version Not Supported'145 }146147 /**148 * Mock XMLHttpRequest requests.149 *150 * mockRequest().and_return('some data', 'text/plain', 200, { 'X-SomeHeader' : 'somevalue' })151 *152 * @return {hash}153 * @api public154 */155156 function mockRequest() {157 return { and_return : function(body, type, status, headers) {158 XMLHttpRequest = MockXMLHttpRequest159 ActiveXObject = false160 status = status || 200161 headers = headers || {}162 headers['content-type'] = type163 JSpec.extend(XMLHttpRequest.prototype, {164 responseText: body,165 responseHeaders: headers,166 status: status,167 statusText: JSpec.statusCodes[status]168 })169 }}170 }171172 /**173 * Unmock XMLHttpRequest requests.174 *175 * @api public176 */177178 function unmockRequest() {179 XMLHttpRequest = OriginalXMLHttpRequest180 ActiveXObject = OriginalActiveXObject181 }182183 JSpec.include({184 name: 'Mock XHR',185186 // --- Utilities187188 utilities : {189 mockRequest: mockRequest,190 unmockRequest: unmockRequest191 },192193 // --- Hooks194195 afterSpec : function() {196 unmockRequest()197 },198199 // --- DSLs200201 DSLs : {202 snake : {203 mock_request: mockRequest,204 unmock_request: unmockRequest,205 last_request: function(){ return lastRequest() }206 }207 }208209 })210})()
deleted:spec/node.js-44 removed
12require.paths.unshift('spec', 'lib', 'spec/lib')3require("jspec")4require("express")5require("express/spec")67function run(specs) {8 specs.forEach(function(spec){9 JSpec.exec('spec/spec.' + spec + '.js')10 })11}1213specs = {14 independant: [15 'core',16 'routing',17 'utils',18 'request',19 'mime',20 'plugins',21 'plugins.cache',22 'plugins.view',23 'plugins.content-length',24 'plugins.method-override',25 'plugins.body-decoder',26 'plugins.redirect',27 'plugins.hooks',28 'plugins.cookie',29 'plugins.session',30 'plugins.flash',31 'plugins.static',32 ]33}3435switch (process.ARGV[2]) {36 case 'all':37 run(specs.independant)38 break39 default: 40 run([process.ARGV[2]])41}4243Express.environment = 'test'44JSpec.run({ reporter: JSpec.reporters.Terminal, failuresOnly: true }).report()
deleted:spec/spec.core.js-93 removed
12describe 'Express'3 describe '.version'4 it 'should be properly formatted'5 Express.version.should.match(/^\d+\.\d+\.\d+$/)6 end7 end8 9 describe 'set()'10 it 'should set an option'11 set('throw exceptions').should.be_null12 set('throw exceptions', true)13 set('throw exceptions').should.be_true14 end15 16 it 'should defer using a function'17 set('root', 'spec')18 set('views', function(){ return set('root') + '/views' })19 set('views').should.eql 'spec/views'20 end21 end22 23 describe 'enable()'24 it 'should enable an option'25 enable('sessions')26 set('sessions').should.be_true27 end28 end29 30 describe 'disable()'31 it 'should disable an option'32 disable('sessions')33 set('sessions').should.be_false34 end35 end36 37 describe 'configure()'38 describe 'given several calls'39 it 'should call them in sequence'40 var order = []41 configure(function(){42 order.push('a')43 })44 configure(function(){45 order.push('b')46 })47 configure('development')48 order.should.eql ['a', 'b']49 end50 51 it 'should call the specific environment only'52 var order = []53 configure('test', function(){54 order.push('a')55 })56 configure('development', function(){57 order.push('b')58 })59 configure('test', function(){60 order.push('c')61 })62 configure('test')63 order.should.eql ['a', 'c']64 end65 66 it 'should call global configurations as well'67 var order = []68 configure(function(){69 order.push('a')70 })71 configure('development', function(){72 order.push('b')73 })74 configure('test', function(){75 order.push('c')76 })77 configure(function(){78 order.push('d')79 })80 configure('test')81 order.should.eql ['a', 'c', 'd']82 end83 end84 85 describe 'given no arguments'86 it 'should throw an error'87 // TODO: tighter spec once JSpec is fixed88 -{ configure() }.should.throw_error89 end90 end91 end92 93end
deleted:spec/spec.mime.js-37 removed
12describe 'Express'3 before4 mime = require('express/mime')5 end6 7 before_each8 reset()9 end10 11 describe 'mime'12 describe 'type()'13 describe 'when given an extension without leading dot'14 it 'should return the associated mime type'15 mime.type('png').should.eql 'image/png'16 end17 end1819 describe 'when given a file path'20 it 'should return the associated mime type'21 mime.type('/path/to/an/image.png').should.eql 'image/png'22 end23 end2425 describe 'when given an unknown extension'26 it 'should default to the "default mime type" setting'27 set('default mime type', 'text/plain')28 mime.type('meow').should.eql 'text/plain'29 end3031 it 'should default to "application/octet-stream" otherwise'32 mime.type('meow').should.eql 'application/octet-stream'33 end34 end35 end36 end37end
deleted:spec/spec.plugins.body-decoder.js-26 removed
12describe 'Express'3 describe 'BodyDecoder'4 describe 'given "application/x-www-form-urlencoded"'5 it 'should parse body as urlencoded params'6 post('/login', function(){7 return this.param('name')8 })9 var response = post('/login', { body: 'name=tj', headers: { 'content-type': 'application/x-www-form-urlencoded' }})10 response.status.should.eql 20011 response.body.should.eql 'tj'12 end13 14 describe 'with charset'15 it 'should parse body as urlencoded params'16 post('/login', function(){17 return this.param('name')18 })19 var response = post('/login', { body: 'name=tj', headers: { 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8' }})20 response.status.should.eql 20021 response.body.should.eql 'tj'22 end23 end24 end25 end26end
deleted:spec/spec.plugins.cache.js-171 removed
12describe 'Express'3 before_each4 reset()5 use(require('express/plugins/cache').Cache)6 cache = require('express/plugins/cache')7 end8 9 describe 'Cache'10 describe 'Request'11 describe '#cache'12 it 'should use memory store by default'13 get('/item', function(){14 return this.cache.toString()15 })16 get('/item').body.should.eql '[Memory Store]'17 end18 end19 end20 end21 22 describe 'cache Store.Memory'23 before_each24 store = new cache.Store.Memory25 end26 27 describe '#toString()'28 it 'should return [Memory Store]'29 store.toString().should.eql '[Memory Store]'30 end31 end32 33 describe '#set()'34 describe 'given a key and value'35 it 'should set the cache data'36 var result37 store.set('foo', 'bar', function(){38 store.get('foo', function(val){39 result = val40 })41 })42 result.should.eql 'bar'43 end44 45 it 'should work with regexp special characters'46 var result,47 result248 store.set('page:/users/1/comments?page=2', 'html', function(){49 store.get('page:/users/1/comments?page=2', function(val){50 result = val51 store.get('page:*', function(vals){52 result2 = vals53 })54 })55 })56 result.should.eql 'html'57 result2.should.eql { 'page:/users/1/comments?page=2': 'html' }58 end59 60 it 'should override existing data'61 var result62 store.set('foo', 'bar', function(){63 store.set('foo', 'baz', function(){64 store.get('foo', function(val){65 result = val66 })67 })68 })69 result.should.eql 'baz'70 end71 end72 73 describe 'given an abitrary key'74 it 'should throw an error'75 -{ store.set({}, 'foo') }.should.throw_error76 end77 end78 79 describe 'given an abitrary value'80 it 'should serialize as JSON'81 var result82 store.set('user', { name: 'tj' }, function(val){83 result = val84 })85 result.should.eql { name: 'tj' }86 end87 end88 end89 90 describe '#get()'91 describe 'given a key'92 it 'should unserialize JSON data'93 var result94 store.set('user', { name: 'tj' }, function(){95 store.get('user', function(val){96 result = val97 })98 })99 result.should.eql { name: 'tj' }100 end101 end102 103 describe 'given wildcards'104 it 'should pass a set of caches'105 var result106 store.set('user:1', 'a', function(){107 store.set('user:2', 'b', function(){108 store.set('foo', 'bar', function(){109 store.get('user:*', function(val){110 result = val111 })112 })113 })114 })115 result.should.eql { 'user:1': 'a', 'user:2': 'b' }116 end117 end118 end119 120 describe '#clear()'121 describe 'given a key'122 it 'should delete previous data'123 var result124 store.set('foo', 'bar', function(){125 store.clear('foo', function(){126 store.get('foo', function(val){127 result = val128 })129 })130 })131 result.should.be_null132 end133 end134 135 describe 'given wildcards'136 it 'should clear a set of caches'137 var results = []138 store.set('user:one', '1', function(){139 store.set('user:two', '2', function(){140 store.clear('user:*', function(){141 store.get('user:one', function(val){142 results.push(val)143 store.get('user:two', function(val){144 results.push(val)145 })146 })147 })148 }) 149 })150 results.should.eql [null, null]151 end152 end153 end154 155 describe '#reap()'156 it 'should destroy caches older than the given age in milliseconds'157 store.set('user:one', '1')158 store.data['user:one'].created = Number((5).minutes.ago)159 store.set('user:two', '2')160 store.data['user:two'].created = Number((2).seconds.ago)161 store.reap((1).minute)162 store.get('user:one', function(val){163 val.should.be_null164 })165 store.get('user:two', function(val){166 val.should.not.be_null167 })168 end169 end170 end171end
deleted:spec/spec.plugins.content-length.js-28 removed
12describe 'Express'3 before_each4 reset()5 use(require('express/plugins/content-length').ContentLength)6 end7 8 describe 'ContentLength'9 describe 'on'10 describe 'response'11 it 'should set the content-length header'12 get('/style.css', function(){13 return 'body { background: #000; }'14 })15 get('/style.css').headers['Content-Length'].should.eql 2616 end17 18 it 'should not override when manually set'19 get('/style.css', function(){20 this.header('Content-Length', 10)21 return 'body { background: #000; }'22 })23 get('/style.css').headers['Content-Length'].should.eql 1024 end25 end26 end27 end28end
deleted:spec/spec.plugins.cookie.js-133 removed
12describe 'Express'3 before_each4 reset()5 use(require('express/plugins/cookie').Cookie)6 compileCookie = require('express/plugins/cookie').compileCookie7 parseCookie = require('express/plugins/cookie').parseCookie8 end9 10 describe 'Cookie'11 describe 'compileCookie()'12 it 'should return a cookie string'13 var options = {14 path: '/',15 domain: '.vision-media.ca'16 }17 compileCookie('foo', 'bar', options).should.eql 'foo=bar; path=/; domain=.vision-media.ca'18 end19 20 it 'should correctly format any Date objects'21 var options = {22 expires: new Date(Date.parse('May 25, 1987 11:13:00 PDT')),23 path: '/foo',24 domain: '.vision-media.ca'25 }26 compileCookie('foo', 'bar', options).should.eql 'foo=bar; expires=Mon, 25 May 1987 18:13:00 GMT; path=/foo; domain=.vision-media.ca'27 end28 29 it 'should convert true to a key without a value'30 var options = {31 path: '/',32 secure: true,33 httpOnly: true34 }35 compileCookie('foo', 'bar', options).should.eql 'foo=bar; path=/; secure; httpOnly'36 end37 38 it 'should compile without options'39 compileCookie('foo', 'bar').should.eql 'foo=bar'40 end41 end42 43 describe 'parseCookie()'44 it 'should parse cookie key/value pairs'45 var attrs = 'sid=1232431234234; data=foo'46 parseCookie(attrs).should.eql { sid: '1232431234234', data: 'foo' }47 end48 49 it 'should preserve case'50 var attrs = 'SID=1232431234234; Data=foo'51 parseCookie(attrs).should.eql { SID: '1232431234234', Data: 'foo' }52 end53 54 it 'should disregard ad-hoc invalid whitespace'55 var attrs = ' SID = 1232431234234 ; data = foo'56 parseCookie(attrs).should.eql { SID: '1232431234234', data: 'foo' }57 end5859 it 'should support complex quoted values'60 var attrs = 'SID="123456789"; fbs_0011223355="uid=0987654321&name=Test+User"'61 parseCookie(attrs).should.eql { SID: '123456789', fbs_0011223355: 'uid=0987654321&name=Test User' }62 end63 64 it 'should not override when a duplicate key is found'65 var attrs = 'SID=1234; SID=9999'66 parseCookie(attrs).should.eql { SID: '1234' }67 end68 69 it 'should support malformed cookies'70 var attrs = 'SID'71 parseCookie(attrs).should.eql {}72 end73 end74 75 describe 'on'76 describe 'request'77 it 'should parse the Cookie header'78 get('/user', function(){79 return this.cookie('foo')80 })81 get('/user', { headers: { cookie: 'foo=bar' }}).body.should.eql 'bar'82 end83 end84 85 describe 'response'86 it 'should populate Set-Cookie'87 get('/user', function(){88 this.cookie('SID', '732423sdfs73243', { path: '/', secure: true })89 return '' 90 })91 get('/user').headers['Set-Cookie'].should.eql 'SID=732423sdfs73243; path=/; secure'92 end93 94 it 'should set multiple cookies'95 get('/user', function(){96 this.cookie('SID', '732423sdfs73243', { path: '/', secure: true })97 this.cookie('foo', 'bar')98 return '' 99 })100 get('/user').headers['Set-Cookie'].should.eql 'SID=732423sdfs73243; path=/; secure\r\nSet-Cookie: foo=bar; path=/'101 end102 103 it 'should delete the cookie'104 get('/user', function(){105 this.cookie('ninja', null)106 this.cookie('pirate', null)107 return '' 108 })109 get('/user').headers['Set-Cookie'].should.eql 'ninja=delete; path=/; expires=Thu, 01 Jan 1970 02:46:40 GMT\r\nSet-Cookie: pirate=delete; path=/; expires=Thu, 01 Jan 1970 02:46:40 GMT'110 end111112 it 'should support URL unfriendly characters'113 get('/user', function(){114 this.cookie('spaceship', '<*==*>', { path: '/', secure: true })115 this.cookie(':)', 'smileyface')116 return '' 117 })118 get('/user').headers['Set-Cookie'].should.eql 'spaceship=%3C*%3D%3D*%3E; path=/; secure\r\nSet-Cookie: %3A)=smileyface; path=/'119 end120 end121 end122 123 describe 'cookie()'124 it 'should get request cookie values'125 get('/user', function(){126 return this.cookie('foo')127 })128 get('/user', { headers: { cookie: 'foo=bar%3D%3D' }}).body.should.eql 'bar=='129 end130 end131 132 end133end
deleted:spec/spec.plugins.flash.js-78 removed
12describe 'Express'3 before_each4 reset()5 use(require('express/plugins/cookie').Cookie)6 use(require('express/plugins/session').Session)7 use(require('express/plugins/flash').Flash)8 Session.store.clear()9 var sess = new Base(123)10 Session.store.commit(sess, function(){})11 end12 13 describe 'Flash'14 describe '#flash()'15 describe 'given a type and msg'16 it 'should push a flash message'17 var headers = { headers: { cookie: 'sid=123' }}18 post('/', function(){ return this.flash('info', 'email sent') })19 get('/', function(){ return this.flash('info').join(', ') })20 post('/', headers)21 post('/', headers)22 get('/', headers).body.should.eql 'email sent, email sent'23 end24 end25 26 describe 'given a type'27 describe 'when no messages have been pushed'28 it 'should return null'29 var headers = { headers: { cookie: 'sid=123' }}30 get('/', function(){ return this.flash('info') || 'empty' })31 get('/', headers).body.should.eql 'empty'32 end33 end34 35 describe 'when messages have been pushed'36 it 'should persist only until flushed'37 var headers = { headers: { cookie: 'sid=123' }}38 post('/', function(){ return this.flash('info', 'email sent') })39 get('/', function(){ return (this.flash('info') || ['nope!']).join(', ') })40 post('/', headers)41 post('/', headers)42 get('/', headers).body.should.eql 'email sent, email sent'43 get('/', headers).body.should.eql 'nope!'44 end45 end46 47 describe 'given no arguments'48 it 'should provide access to all types'49 var flash, headers = { headers: { cookie: 'sid=123' }}50 post('/', function(){ return this.flash('info', 'email sent') })51 post('/error', function(){ return this.flash('error', 'email failed to send') })52 get('/', function(){ return flash = this.flash(), '' })53 post('/', headers)54 post('/', headers)55 post('/error', headers)56 get('/')57 flash.should.eql { info: ['email sent', 'email sent'], error: ['email failed to send'] }58 end59 60 it 'should persist only until flushed'61 var flash, headers = { headers: { cookie: 'sid=123' }}62 post('/', function(){ return this.flash('info', 'email sent') })63 post('/error', function(){ return this.flash('error', 'email failed to send') })64 get('/', function(){ return flash = this.flash(), '' })65 post('/', headers)66 post('/', headers)67 post('/error', headers)68 get('/', headers)69 flash.should.eql { info: ['email sent', 'email sent'], error: ['email failed to send'] }70 get('/', headers)71 flash.should.eql {}72 end73 end74 75 end76 end77 end78end
deleted:spec/spec.plugins.hooks.js-46 removed
12describe 'Express'3 before_each4 reset()5 hooks = require('express/plugins/hooks')6 use(hooks.Hooks)7 hooks.callbacks.before = []8 hooks.callbacks.after = []9 end10 11 describe 'Hooks'12 describe 'before()'13 it 'should be called before every request'14 GLOBAL.before(function(){15 this.response.body = 'foo'16 })17 GLOBAL.before(function(){18 this.response.body += 'bar'19 })20 get('/user', function(){})21 get('/user').body.should.eql 'foobar'22 end23 24 it 'should be able to halt the request'25 GLOBAL.before(function(){26 this.respond(404, 'woo!')27 })28 get('/user', function(){ return 'fail' })29 get('/user').status.should.eql 40430 get('/user').body.should.eql 'woo!'31 end32 end33 34 describe 'after()'35 it 'should be called after every request'36 var body37 GLOBAL.after(function(){38 body = this.response.body39 })40 get('/user', function(){ return 'test' })41 get('/user').body.should.eql 'test'42 body.should.eql 'test'43 end44 end45 end46end
deleted:spec/spec.plugins.js-41 removed
12var mime = require('express/mime')34CSSColors = Plugin.extend({5 extend: {6 init: function() {7 this.initialized = true8 }9 },10 on: {11 response: function(event) {12 if (event.response.headers['Content-Type'] === mime.type('css'))13 event.response.body = event.response.body.replace('black', '#000')14 }15 }16})1718describe 'Express'19 describe 'use()'20 before_each21 reset()22 use(CSSColors)23 end24 25 it 'should call .init on plugins when available'26 CSSColors.initialized.should.be_true27 end28 29 describe 'events'30 describe 'response'31 it 'should be triggered before headers and body are sent'32 get('/style.css', function(){33 this.contentType('css')34 return 'body { color: black; }'35 })36 get('/style.css').body.should.eql 'body { color: #000; }'37 end38 end39 end40 end41end
deleted:spec/spec.plugins.method-override.js-27 removed
12describe 'Express'3 before_each4 reset()5 use(require('express/plugins/method-override').MethodOverride)6 end7 8 describe 'MethodOverride'9 describe 'on'10 describe 'request'11 it 'should consider _method as the HTTP method'12 put('/user', function(){13 return 'updated user'14 })15 post('/user', { body: '_method=put', headers: { 'content-type': 'application/x-www-form-urlencoded' }}).body.should.eql 'updated user'16 end17 18 it 'should force _method to lowercase to conform to internal uses'19 put('/user', function(){20 return 'updated user'21 })22 post('/user', { body: '_method=PUT', headers: { 'content-type': 'application/x-www-form-urlencoded' }}).body.should.eql 'updated user'23 end24 end25 end26 end27end
deleted:spec/spec.plugins.redirect.js-70 removed
12describe 'Express'3 before_each4 reset()5 use(require('express/plugins/redirect').Redirect)6 end7 8 describe 'Redirect'9 describe 'redirect()'10 it 'should set status to 303'11 get('/logout', function(){12 this.redirect('/')13 })14 get('/logout').status.should.eql 30315 get('/logout').headers['Location'].should.eql '/'16 end17 18 it 'should allow optional status code'19 get('/logout', function(){20 this.redirect('/', 304)21 })22 get('/logout').status.should.eql 30423 get('/logout').headers['Location'].should.eql '/'24 end25 end26 27 describe 'redirect("back")'28 it 'should check Referrer header'29 get('/logout', function(){30 this.redirect('back')31 })32 var response = get('/logout', { headers: { referrer: '/login' }})33 response.headers['Location'].should.eql '/login'34 end35 36 it 'should check referer header'37 get('/logout', function(){38 this.redirect('back')39 })40 var response = get('/logout', { headers: { referer: '/login' }})41 response.headers['Location'].should.eql '/login'42 end43 end44 45 describe 'redirect(home)'46 it 'should check set("home")'47 set('home', '/login')48 get('/logout', function(){49 this.redirect('home')50 })51 get('/logout').headers['Location'].should.eql '/login'52 end53 54 it 'should check set("basepath")'55 set('basepath', '/web/')56 get('/logout', function(){57 this.redirect('home')58 })59 get('/logout').headers['Location'].should.eql '/web/'60 end61 62 it 'should default to "/"'63 get('/logout', function(){64 this.redirect('home')65 })66 get('/logout').headers['Location'].should.eql '/'67 end68 end69 end70end
deleted:spec/spec.plugins.session.js-140 removed
12describe 'Express'3 before_each4 reset()5 use(require('express/plugins/cookie').Cookie)6 use(Session = require('express/plugins/session').Session)7 Base = require('express/plugins/session').Base8 Session.store.clear()9 end10 11 describe 'Session'12 describe 'when sid cookie is not present'13 it 'should set sid cookie'14 get('/login', function(){ return '' })15 get('/login').headers['Set-Cookie'].should.match(/^sid=(\w+);/)16 end17 18 describe 'and requesting /favicon.ico'19 it 'should not set sid cookie'20 get('/favicon.ico', function(){ this.respond() })21 get('/favicon.ico').headers.should.not.have_property 'set-cookie'22 end23 end24 end25 26 describe 'when existing sid cookie is present'27 it 'should not set sid'28 Session.store.commit(new Base(123))29 get('/login', function(){ return '' })30 get('/login', { headers: { cookie: 'sid=123' }}).headers.should.not.have_property 'Set-Cookie'31 end32 end33 34 describe 'when unknown sid cookie is present'35 it 'should set new sid'36 get('/login', function(){ return '' })37 var headers= get('/login', { headers: { cookie: 'sid=123' }}).headers38 39 headers.should.have_property 'Set-Cookie'40 headers['set-cookie'].should.not.be '123'41 end42 end 4344 describe 'session Store.Memory'45 before_each46 Session.store= memory = new (require('express/plugins/session').Store.Memory)47 end48 49 it 'should persist'50 post('/login', function(){51 return this.session.name = 'tj'52 })53 get('/login', function(){54 return this.session.name55 })56 memory.commit(new Base(123))57 var headers = { headers: { cookie: 'sid=123' }}58 post('/login', headers)59 get('/login', headers).status.should.eql 20060 get('/login', headers).body.should.eql 'tj'61 end62 63 describe '#toString()'64 it 'should return [Memory Store]'65 memory.toString().should.eql '[Memory Store]'66 end67 end68 69 describe '#fetch()'70 describe 'when the session does not exist'71 it 'should return a new Session'72 var result73 memory.fetch('1', function(error,session){74 result= session75 })76 result.should.have_property 'lastAccess'77 end78 end79 80 describe 'when the session does exist'81 it 'should return the previous session'82 var result83 memory.commit(new Base('1'))84 memory.fetch('1', function(error, session){85 result = session86 })87 result.id.should.eql '1'88 end89 end90 end91 92 describe '#clear()'93 it 'should remove all sessions'94 memory.commit({ id: '1' })95 memory.commit({ id: '2' })96 memory.clear()97 memory.should.not.have_property '1'98 memory.should.not.have_property '2'99 end100 end101 102 describe '#length()'103 it 'should return the number of session'104 var length105 memory.commit({ id: '1' })106 memory.commit({ id: '2' })107 memory.length(function(error, len) {108 length = len109 })110 length.should.eql 2111 end112 end113 114 describe '#destroy()'115 it 'should destroy a single session'116 memory.commit({ id: '1' })117 memory.commit({ id: '2' })118 memory.destroy('1')119 memory.store.should.not.have_property '1'120 memory.store.should.have_property '2'121 end122 end123 124 describe '#reap()'125 it 'should destroy sessions older than the given age in milliseconds'126 memory.commit({ id: '1', lastAccess: Number(new Date) - 300 })127 memory.commit({ id: '2', lastAccess: Number(new Date) - 250 })128 memory.commit({ id: '3', lastAccess: Number(new Date) - 100 })129 memory.commit({ id: '4', lastAccess: Number(new Date) })130 memory.reap(200)131 memory.store.should.not.have_property '1'132 memory.store.should.not.have_property '2'133 memory.store.should.have_property '3'134 memory.store.should.have_property '4'135 end136 end137 end138 139 end140end
deleted:spec/spec.plugins.static.js-73 removed
12describe 'Express'3 describe 'Static'4 before5 use(require('express/plugins/static').Static, { path: 'spec/fixtures' })6 end7 8 // TODO: spec again when JSpec has async support ... mocking out FileReadStream9 // is to much of a hassle10 11 // describe 'GET /public/*'12 // it 'should transfer static files'13 // get('/public/user.json').body.should.include '"name":'14 // end15 // end16 // 17 // describe '#sendfile()'18 // describe 'when the file exists'19 // it 'should throw an InvalidPathError when .. is found'20 // get('/public/*', function(file){21 // this.sendfile(file)22 // })23 // try { get('/public/../foobar') }24 // catch (e) {25 // e.name.should.eql 'InvalidPathError'26 // e.message.should.eql "`spec/fixtures/../foobar' is not a valid path"27 // }28 // end29 // 30 // it 'should transfer the file'31 // get('/public/*', function(file){32 // this.sendfile('spec/fixtures/' + file)33 // })34 // get('/public/user.json').body.should.include '"name":'35 // end36 // 37 // it 'should automatically set the content type based on extension'38 // get('/public/*', function(file){39 // this.sendfile('spec/fixtures/' + file)40 // })41 // get('/public/user.json').headers['content-type'].should.eql 'application/json'42 // end43 // end44 // end45 // 46 // describe '#download()' 47 // describe 'when the file exists'48 // it 'should set attachment filename'49 // get('/report', function(){50 // this.download('report.pdf')51 // return 'foo'52 // })53 // get('/report').headers['content-disposition'].should.eql 'attachment; filename="report.pdf"'54 // end55 // 56 // it 'should transfer the file'57 // get('/public/*', function(file){58 // this.download('spec/fixtures/' + file)59 // })60 // get('/public/user.json').body.should.include '"name":'61 // end62 // 63 // it 'should automatically set the content type based on extension'64 // get('/public/*', function(file){65 // this.download('spec/fixtures/' + file)66 // })67 // get('/public/user.json').headers['content-type'].should.eql 'application/json'68 // end69 // end70 // end71 // 72 end73end
deleted:spec/spec.plugins.view.js-294 removed
12ejs = require('ejs')3helpers = require('express/plugins/view').helpers45describe 'Express'6 before_each7 reset()8 end9 10 describe 'View'11 describe 'set("views")'12 it 'should default to <root>/views'13 set('root', 'spec')14 set('views').should.eql 'spec/views'15 end16 end17 18 describe 'set("partials")'19 it 'should default to <views>/partials'20 set('root', 'spec')21 set('partials').should.eql 'spec/views/partials'22 set('views', 'magicland')23 set('partials').should.eql 'magicland/partials'24 end25 end26 27 describe 'ejs'28 it 'should work without options'29 var str = '<h2><%= "Title" %></h2>'30 ejs.render(str).should.eql '<h2>Title</h2>'31 end32 33 it 'should work with locals'34 var str = '<h2><%= title %></h2>'35 ejs.render(str, { locals: { title: 'Title' }}).should.eql '<h2>Title</h2>'36 end37 end38 39 describe '#partial()'40 before_each41 set('views', 'spec/fixtures')42 set('partials', 'spec/fixtures/partials')43 end44 45 describe 'given a valid view name'46 describe 'with EJS'47 it 'should render a partial'48 get('/', function(){49 this.render('list.html.ejs', { locals: { items: ['foo', 'bar'] }})50 })51 get('/').body.should.include '<ul>'52 get('/').body.should.include '<li>foo'53 get('/').body.should.include '<li>bar'54 end55 56 it 'should render collections'57 get('/', function(){58 return this.partial('item.html.ejs', {59 collection: ['foo', 'bar']60 })61 })62 get('/').body.should.include '<li>foo'63 get('/').body.should.include '<li>bar'64 end65 66 it 'should render collections with a given object name'67 get('/', function(){68 return this.partial('video.html.ejs', {69 collection: ['im a movie', 'im another movie'],70 as: 'vid'71 })72 })73 get('/').body.should.include '<li>im a movie'74 get('/').body.should.include '<li>im another movie'75 end76 77 it 'should pass __isFirst__, __isLast__, and __index__ to partials as locals'78 get('/', function(){79 return this.partial('article.html.ejs', {80 collection: ['a', 'b', 'c']81 })82 })83 get('/').body.should.include '<li class="first">a'84 get('/').body.should.include '<li class="1">b'85 get('/').body.should.include '<li class="last">c'86 end87 end88 describe 'with Haml'89 it 'should render a partial'90 get('/', function(){91 this.render('list.html.haml', { locals: { items: ['foo', 'bar'] }})92 })93 get('/').body.should.include '<ul>'94 get('/').body.should.include '<li>foo'95 get('/').body.should.include '<li>bar'96 end97 98 it 'should render collections'99 get('/', function(){100 return this.partial('item.html.haml', {101 collection: ['foo', 'bar']102 })103 })104 get('/').body.should.include '<li>foo'105 get('/').body.should.include '<li>bar'106 end107 108 it 'should render collections with a given object name'109 get('/', function(){110 return this.partial('video.html.haml', {111 collection: ['im a movie', 'im another movie'],112 as: 'vid'113 })114 })115 get('/').body.should.include '<li>im a movie'116 get('/').body.should.include '<li>im another movie'117 end118 119 it 'should pass __isFirst__, __isLast__, and __index__ to partials as locals'120 get('/', function(){121 return this.partial('article.html.haml', {122 collection: ['a', 'b', 'c']123 })124 })125 get('/').body.should.include '<li class="first">a'126 get('/').body.should.include '<li class="1">b'127 get('/').body.should.include '<li class="last">c'128 end129 end130 end131 end132 133 describe '#render()'134 before_each135 set('views', 'spec/fixtures')136 end137 138 describe 'given a callback'139 it 'should be passed the rendered content'140 get('/', function(){141 this.render('hello.html.haml', {}, function(err, content){142 if (err) this.error(err)143 else this.respond(203, content)144 })145 })146 get('/').body.should.include '<html>\n<body>'147 get('/').status.should.eql 203148 end149 end150 151 describe 'given a valid view name'152 describe 'and layout of the same type exists'153 it 'should render the layout and view'154 get('/', function(){155 this.render('hello.html.haml')156 })157 get('/').body.should.include '<html>\n<body>'158 get('/').body.should.include '<h2>Hello'159 end160 161 it 'should default context to the current request'162 get('/', function(){163 this.title = 'Welcome'164 this.render('page.html.haml', { layout: false })165 })166 get('/').body.should.include '<title>Welcome'167 end168 169 it 'should set the content type based on the last path segment'170 get('/', function(){171 this.render('hello.html.haml')172 })173 get('/').headers['Content-Type'].should.eql 'text/html'174 end175 end176 177 describe 'and layout of the same type does not exist'178 it 'should throw an error'179 get('/', function(){180 this.render('hello.html.haml', { layout: 'front' })181 })182 -{ get('/') }.should.throw_error "ENOENT, No such file or directory 'spec/fixtures/front.html.haml'"183 end184 end185 186 describe 'given a custom layout name'187 it 'should render the layout and view'188 get('/', function(){189 this.title = 'Express'190 this.render('hello.html.haml', { layout: 'page' })191 })192 get('/').body.should.include '<title>Express'193 get('/').body.should.include '<h2>Hello'194 end195 end196 197 describe 'given a full layout name'198 it 'should render a layout of a different engine'199 get('/', function(){200 this.render('hello.html.haml', { layout: 'layout.html.ejs' })201 })202 get('/').body.should.include '<h2>Hello'203 get('/').body.should.include '<p>'204 end205 end206 207 describe 'when layout: false'208 it 'should render the view only'209 get('/', function(){210 this.render('hello.html.haml', { layout: false })211 })212 get('/').body.should.not.include '<body>'213 get('/').body.should.include '<h2>Hello'214 end215 end216 217 describe 'when a global is set'218 it 'should include the helper and translate the text in the view'219 helpers._ = function(text){220 if (text == 'Hello world') return 'Hola mundo'221 }222 get('/', function(){223 this.render('helpers.html.haml', { layout: false })224 })225 get('/').body.should.include 'Hola mundo'226 end227 it 'should include the helper and translate the text in the layout'228 helpers._ = function(text){229 if (text == 'Testing') return 'Probando'230 }231 get('/', function(){232 this.render('helpers-layout.html.haml', { layout: 'layout-helper' })233 })234 get('/').body.should.include 'Probando'235 end236 end237 238 describe 'when engine cannot be found'239 it 'should throw an error'240 get('/', function(){241 this.render('user.html.invalid')242 })243 -{ get('/') }.should.throw_error "Cannot find module 'invalid'"244 end245 end246 247 describe 'when locals are passed'248 it 'should have direct access to locals'249 get('/user', function(){250 this.render('user.html.haml', {251 locals: {252 name: 'tj',253 email: 'tj@vision-media.ca'254 }255 })256 })257 get('/user').body.should.include '<h1>tj'258 get('/user').body.should.include '<p>tj@vision-media.ca'259 end260 261 it 'should have direct access to locals within the layout'262 get('/user', function(){263 this.render('user.html.haml', {264 layout: 'layout-user',265 locals: {266 name: 'tj',267 email: 'tj@vision-media.ca'268 }269 })270 })271 get('/user').body.should.include '<title>Viewing tj'272 get('/user').body.should.include '<h1>tj'273 get('/user').body.should.include '<p>tj@vision-media.ca'274 end275 end276 277 describe 'when context is passed'278 it 'should evaluate in context to that object'279 get('/article', function(){280 this.render('article.html.haml', {281 context: {282 name: 'Writing a Node.js Web Application'283 }284 })285 })286 get('/article').body.should.include '<h2>Writing a Node.js Web Application'287 end288 end289 290 end291 292 end293 end294end
deleted:spec/spec.request.js-394 removed
12describe 'Express'3 before_each4 reset()5 end6 7 describe 'Request'8 describe '#status()'9 it 'should set the response status'10 get('/user', function(){ this.status(500) })11 get('/user').status.should.eql 50012 end13 end14 15 describe '#charset'16 describe 'when defined'17 it 'should append "; charset=CHARSET'18 get('/user', function(){19 this.contentType('html')20 this.charset = 'UTF-8'21 return '∂'22 })23 get('/user').headers['Content-Type'].should.eql 'text/html; charset=UTF-8'24 end25 end26 end2728 describe '#header()'29 describe 'when given a field name and value'30 it 'should set the header'31 get('/user', function(){32 this.header('x-foo', 'bar')33 })34 get('/user').headers.should.have_property 'x-foo', 'bar'35 end 36 end3738 describe 'when given a field name'39 it 'should return a request header value'40 get('/user', function(){41 return this.header('host')42 })43 get('/user').body.should.eql 'localhost'44 end4546 it 'should be case-insensitive'47 get('/user', function(){48 return this.header('Host')49 })50 get('/user').body.should.eql 'localhost'51 end52 end53 end54 55 describe '#isXHR'56 it 'should return false unless X-Requested-With is "XMLHttpRequest"'57 get('/', function(){ return this.isXHR ? 'yay' : 'nope' })58 get('/').body.should.eql 'nope'59 end60 61 it 'should return true when X-Requested-With is "XMLHttpRequest"'62 get('/', function(){ return this.isXHR ? 'yay' : 'nope' })63 get('/', { headers: { 'x-requested-with': 'XMLHttpRequest' }}).body.should.eql 'yay'64 end65 66 it 'should be case insensitive'67 get('/', function(){ return this.isXHR ? 'yay' : 'nope' })68 get('/', { headers: { 'x-requested-with': 'xmlhttprequest' }}).body.should.eql 'yay'69 end70 end71 72 describe '#accepts()'73 describe 'when the Accept header is present'74 it 'should return true if the mime type is acceptable'75 get('/user', function(){ return this.accepts('jpeg').toString() })76 get('/user', { headers: { accept: 'image/jpeg' }}).body.should.eql 'true'77 end78 79 it 'should return false if the mime type is not present'80 get('/user', function(){ return this.accepts('html').toString() })81 get('/user', { headers: { accept: 'image/jpeg' }}).body.should.eql 'false'82 end83 end84 85 describe 'when the Accept header is not present'86 it 'should return true'87 get('/user', function(){ return this.accepts('jpeg').toString() })88 get('/user', { headers: { accept: '' }}).body.should.eql 'true'89 end90 end91 92 describe 'should allow multiple arguments'93 it 'should return true if any mime type is present'94 get('/user', function(){ return this.accepts('jpeg', 'png').toString() })95 get('/user', { headers: { accept: 'image/gif,image/png' }}).body.should.eql 'true'96 end97 98 it 'should return false if none of the mime types are present'99 get('/user', function(){ return this.accepts('jpeg', 'png').toString() })100 get('/user', { headers: { accept: 'text/plain,text/html' }}).body.should.eql 'false'101 end102 end103 104 describe 'when a media type range was sent'105 it 'should return true if the group media type matches'106 get('/user', function(){ return this.accepts('html').toString() })107 get('/user', { headers: { accept: 'text/plain,text/*' }}).body.should.eql 'true'108 end109 it 'should return false if the group media type does not match'110 get('/user', function(){ return this.accepts('ogg').toString() })111 get('/user', { headers: { accept: 'text/plain,text/*' }}).body.should.eql 'false'112 end113 end114 end115 116 describe '#contentType()'117 it 'should set Content-Type header with mime type passed'118 get('/style.css', function(){119 this.contentType('css')120 return 'body { background: white; }'121 })122 get('/style.css').headers['Content-Type'].should.eql 'text/css'123 end124 end125 126 describe '#attachment()'127 it 'should set Content-Disposition to attachment'128 get('/report', function(){129 this.attachment()130 return 'foo'131 })132 get('/report').headers['Content-Disposition'].should.eql 'attachment'133 end134135 it 'should set attachment filename'136 get('/report', function(){137 this.attachment('report.pdf')138 return 'foo'139 })140 get('/report').headers['Content-Disposition'].should.eql 'attachment; filename="report.pdf"'141 end142 end143144 describe '#param()'145 it 'should return a route placeholder value'146 get('/user/:id', function(){147 return 'user ' + this.param('id')148 })149 get('/user/12').body.should.eql 'user 12'150 end151152 it 'should return several route placeholder values'153 get('/user/:id/:operation', function(){154 return this.param('operation') + 'ing user ' + this.param('id') 155 })156 get('/user/12/edit').body.should.eql 'editing user 12'157 end158159 it 'should allow optional placeholders'160 get('/user/:id?', function(){161 return this.param('id') ? 'user ' + this.param('id') : 'users'162 })163 get('/user/12').body.should.eql 'user 12'164 get('/user').body.should.eql 'users'165 end166167 it 'should allow placeholders as part of a segment'168 get('/report.:format', function(){169 return 'report as ' + this.param('format')170 })171 get('/report.csv').body.should.eql 'report as csv'172 get('/report.pdf').body.should.eql 'report as pdf'173 end174175 it 'should allow optional placeholders in middle segments'176 get('/user/:id?/edit', function(){177 return this.param('id') ? 'editing ' + this.param('id') : 'editing your account'178 })179 get('/user/12/edit').body.should.eql 'editing 12'180 get('/user/edit').body.should.eql 'editing your account'181 end182183 it 'should work with several routes'184 get('/user/:id', function(){ return this.param('id') })185 get('/product/:name', function(){ return this.param('name') })186 get('/user/12').body.should.eql '12'187 get('/product/ipod').body.should.eql 'ipod'188 end189190 it 'should work with a query string'191 get('/user', function(){192 var page = this.param('page')193 return page === undefined ? 'First page' : String(page)194 })195 get('/user').body.should.eql 'First page'196 get('/user?page=0').body.should.eql '0'197 get('/user?page=2').body.should.eql '2'198 get('/user?foo[]=bar&page=5').body.should.eql '5'199 end200201 it 'should work with splats'202 get('/:path/*.*', function(path, file, ext){203 return [path, file, ext].join(', ')204 })205 get('/public/app.js').body.should.eql 'public, app, js'206 end207 end208 209 describe '#pass()'210 it 'should pass control to the next matching route'211 get('/user', function(){ 212 this.pass()213 })214 get('/user', function(){215 this.pass()216 return 'nodejs'217 })218 get('/user', function(){ return 'success'})219 get('/user').body.should.eql 'success'220 end221 222 describe 'given a string'223 it 'should pass to the given route'224 get('/user', function(){225 this.pass('/user/1')226 })227 get('/user/:id', function(){228 return 'Supa doopa usa'229 })230 get('/user').body.should.eql 'Supa doopa usa'231 end232 end233 end234 235 describe '#error()'236 describe 'when an error route is defined'237 it 'should be called'238 var err239 disable('throw exceptions')240 global.error(function(e){241 err = e242 this.respond(500, 'FAIL!')243 })244 get('/', function(){ this.error(new Error('whoop')) })245 get('/').body.should.eql 'FAIL!'246 err.message.should.eql 'whoop'247 end248 end249 250 describe 'when not accepting common mime types'251 it 'should render the default 500 status body'252 var headers = { headers: { accept: 'text/xml' }}253 disable('throw exceptions')254 enable('show exceptions')255 get('/', function(){256 this.error(new Error('fail!'))257 })258 get('/', headers).body.should.eql 'Internal Server Error'259 get('/', headers).status.should.eql 500260 end261 end262 263 describe 'when accepting "html"'264 describe 'with "show exceptions" enabled'265 it 'should render the show-exceptions page'266 disable('throw exceptions')267 enable('show exceptions')268 get('/', function(){269 this.error(new Error('fail!'))270 })271 get('/').body.should.include '<em>500</em> Error: fail!'272 get('/').status.should.eql 500273 end274 275 it 'should render the show-exceptions page with errors thrown within the route'276 disable('throw exceptions')277 enable('show exceptions')278 get('/', function(){279 throw new Error('fail!')280 })281 get('/').body.should.include '<em>500</em> Error: fail!'282 get('/').status.should.eql 500283 end284 end285 286 describe 'with "throw exceptions" enabled'287 it 'should re-throw the exception'288 enable('show exceptions')289 enable('throw exceptions')290 get('/', function(){291 this.error(new Error('fail!'))292 })293 -{ get('/') }.should.throw_error Error, 'fail!'294 end295 end296 end297 298 describe 'when accepting "text/plain"'299 describe 'with "show exceptions" enabled'300 it 'should render a text representation of the error'301 disable('throw exceptions')302 enable('show exceptions')303 get('/', function(){304 this.error(new Error('fail!'))305 })306 get('/', { headers: { accept: 'text/plain' }}).body.should.include '500 Error: fail!'307 get('/').status.should.eql 500308 end309 end310 end311 312 describe 'when accepting "application/json"'313 describe 'with "show exceptions" enabled'314 it 'should render a text representation of the error'315 disable('throw exceptions')316 enable('show exceptions')317 get('/', function(){318 this.error(new Error('fail!'))319 })320 get('/', { headers: { accept: 'application/json' }}).body.should.include '{"error":{"message":"fail!"'321 get('/').status.should.eql 500 322 end323 end324 end325 326 describe 'with "show exceptions" disabled'327 it 'should render the default 500 status body'328 disable('throw exceptions')329 get('/', function(){330 this.error(new Error('fail!'))331 })332 get('/').body.should.eql 'Internal Server Error'333 get('/').status.should.eql 500334 end335 end336 337 describe 'with "throw exceptions" enabled'338 it 'should re-throw the exception'339 enable('throw exceptions')340 get('/', function(){341 this.error(new Error('fail!'))342 })343 -{ get('/') }.should.throw_error Error, 'fail!'344 end345 end346 end347 348 describe '#notFound()'349 describe 'when a notFound route is defined'350 it 'should be called'351 notFound(function(){352 this.respond(404, 'Sorry your page was not found')353 })354 get('/', function(){ this.notFound() })355 get('/').body.should.eql 'Sorry your page was not found'356 end357 end358 359 describe 'when accepting "html"'360 describe 'with "helpful 404" enabled'361 it 'should render the not-found page'362 enable('helpful 404')363 get('/', function(){ this.notFound() })364 get('/').body.should.include '<em>404</em> Not Found'365 get('/').status.should.eql 404366 end367 end368 end369 370 describe 'when not accepting "html"'371 describe 'with "helpful 404" enabled'372 it 'should render defaulat 404 status body'373 var headers = { headers: { accept: 'text/plain' }}374 enable('helpful 404')375 get('/', function(){ this.notFound() })376 get('/', headers).body.should.eql 'Not Found'377 get('/', headers).status.should.eql 404378 end379 end380 end381 382 describe 'when "helpful 404" is disabled'383 it 'should render defaulat 404 status body'384 var headers = { headers: { accept: 'text/plain' }}385 enable('helpful 404')386 get('/', function(){ this.notFound() })387 get('/', headers).body.should.eql 'Not Found'388 get('/', headers).status.should.eql 404389 end390 end391 end392 393 end394end
deleted:spec/spec.routing.js-381 removed
12describe 'Express'3 before_each4 reset()5 end6 7 describe 'param()'8 describe 'given no args'9 it 'should throw an error'10 -{ param() }.should.throw_error TypeError11 end12 end13 14 describe 'given a non-string as the first argument'15 it 'should throw an error'16 -{ param(12) }.should.throw_error TypeError17 end18 end19 20 describe 'given no callback function'21 it 'should throw an error'22 -{ param('foo') }.should.throw_error TypeError23 end24 end25 26 describe 'given a non-function as the second argument'27 it 'should throw an error'28 -{ param('foo', 2) }.should.throw_error TypeError29 end30 end31 32 describe 'with key / callback function'33 it 'should pre-process a value before it is passed to a route'34 param('user_id', function(val){35 val = parseInt(val)36 return isNaN(val) ? false : val37 })38 get('/user/:user_id', function(id){39 return String(typeof id === 'number')40 })41 get('/user/99').body.should.eql 'true'42 end43 44 it 'should pass when false is explictly returned'45 param('user_id', function(val){46 val = parseInt(val)47 return isNaN(val) ? false : val48 })49 get('/user/:user_id', function(id){50 return String(typeof id === 'number')51 })52 get('/user/:name', function(name){53 return name54 })55 get('/user/99').body.should.eql 'true'56 get('/user/tj').body.should.eql 'tj'57 end58 59 it 'should evaluate in context to the request'60 param('user_id', function(val){61 this.pass()62 })63 get('/user/:user_id', function(id){64 return String(typeof id === 'number')65 })66 get('/user/99').status.should.eql 40467 end68 end69 end70 71 describe 'route'72 describe 'with callback function'73 it 'should respond with a body string'74 get('/user', function(){75 return 'test'76 })77 get('/user').body.should.eql 'test'78 end79 end80 81 describe 'with options and callback function'82 it 'should respond with a body string'83 get('/user', {}, function(){84 return 'test with options'85 })86 get('/user').body.should.eql 'test with options'87 end88 end89 90 describe 'with a trailing slash in request path'91 it 'should still match'92 get('/user', {}, function(){93 return 'test with options'94 })95 get('/user/').body.should.eql 'test with options'96 end97 end98 99 describe 'with a trailing slash in route path'100 it 'should still match'101 get('/user/', {}, function(){102 return 'test with options'103 })104 get('/user').body.should.eql 'test with options'105 end106 end107 108 describe 'with a trailing whitespace in request path'109 it 'should still match'110 get('/user', {}, function(){111 return 'test with options'112 })113 get('/user/ ').body.should.eql 'test with options'114 end115 end116 117 describe 'with a trailing whitespace in route path'118 it 'should still match'119 get('/user/ ', {}, function(){120 return 'test with options'121 })122 get('/user').body.should.eql 'test with options'123 end124 end125 126 describe 'with several similar routes'127 it 'should match them properly'128 get('/foo', function(){129 return 'bar'130 })131 get('/foos', function(){132 return 'baz'133 })134 get('/foo').body.should.eql 'bar'135 get('/foos').body.should.eql 'baz'136 end137 end138 139 describe 'with several identical routes'140 it 'should match the first route'141 get('/foo', function(){142 return 'bar'143 })144 get('/foo', function(){145 return 'baz'146 })147 get('/foo').body.should.eql 'bar'148 end149 end150 151 describe 'with regular expression'152 it 'should match'153 get(/^\/user\/(\d+)\/(\w+)/, function(id, operation){154 return [id, operation].join(', ')155 })156 get('/user/12/edit').body.should.eql '12, edit'157 get('/user/12').status.should.eql 404158 end159 end160 161 describe 'with a wild-card'162 it 'should still match'163 get('/user/:id', function(){ return 'yay' })164 get('/user/12').body.should.eql 'yay'165 end166 167 it 'should not match with an additional path segment'168 get('/user/:id', function(){ return 'yay' })169 get('/user/12/edit').body.should.eql 'Not Found'170 end171 172 it 'should pass it to the route function'173 get('/user/:id', function(id){174 return id175 })176 get('/user/12').body.should.eql '12'177 end178 end179 180 describe 'with several wild-cards'181 it 'should still match'182 get('/user/:id/:op', function(){ return 'yay' })183 get('/user/12/edit').body.should.eql 'yay'184 end185 186 it 'should pass them to the route function'187 get('/user/:id/:op', function(id, op){188 return op + 'ing user ' + id189 })190 get('/user/12/edit').body.should.eql 'editing user 12'191 end192 end193 194 describe 'with an optional wild-card'195 it 'should match with a value'196 get('/user/:id?', function(){ return 'yay' })197 get('/user/1').body.should.eql 'yay'198 end199 200 it 'should pass it to the route function'201 get('/user/:id?', function(id){202 return id || 'You'203 })204 get('/user/12').body.should.eql '12'205 get('/user').body.should.eql 'You'206 end207 208 it 'should match without a value'209 get('/user/:id?', function(){ return 'yay' })210 get('/user').body.should.eql 'yay'211 end212 213 it 'should not match with an additional path segment'214 get('/user/:id?', function(){ return 'yay' })215 get('/user/12/edit').body.should.eql 'Not Found'216 end217 218 it 'should match without leading character'219 get('/report.:format?', function(format){ return format || 'none' })220 get('/report.csv').body.should.eql 'csv'221 get('/report').body.should.eql 'none'222 end223 224 it 'should allow common regexp literals'225 get('/user/(\\d+)', function(id){ return id })226 get('/user/12').body.should.eql '12'227 get('/user/asdf').status.should.eql 404228 end229 230 end231 232 describe 'with partial wild-card'233 it 'should still match'234 get('/report.:format', function(){235 return 'yay'236 })237 get('/report.csv').body.should.eql 'yay'238 get('/report.pdf').body.should.eql 'yay'239 end240 241 it 'should match when mid-segment'242 get('/user-:name-:id', function(name, id){243 return name + ' ' + id244 })245 get('/user-tj-1').body.should.eql 'tj 1'246 get('/user--1').status.should.eql 404247 get('/user-tj-').status.should.eql 404248 end249 250 it 'should not match without value'251 get('/report.:format', function(){252 return 'yay'253 })254 get('/report.').body.should.eql 'Not Found'255 end256 end257 258 describe 'with a single splat'259 it 'should match a single segment'260 get('/public/*', function(file){261 return file262 })263 get('/public/app.js').body.should.eql 'app.js'264 end265 266 it 'should not match when there is nothing to capture'267 get('/public/*', function(file){268 return file269 })270 get('/public/').status.should.eql 404271 get('/public').status.should.eql 404272 end273 274 it 'should match a multiple segments'275 get('/public/*', function(file){276 return file277 })278 get('/public/javascripts/app.js').body.should.eql 'javascripts/app.js'279 end280 end281 282 describe 'with several splats'283 it 'should greedily match'284 get('/public/*.*', function(path, ext){285 return 'path: ' + path + ' ext: ' + ext286 })287 get('/public/app.js').body.should.eql 'path: app ext: js'288 end289 290 it 'should not match when there is nothing to capture'291 get('/public/*.*', function(file){292 return file293 })294 get('/public/foo.').status.should.eql 404295 get('/public/foo').status.should.eql 404296 get('/public/').status.should.eql 404297 get('/public').status.should.eql 404298 end299 300 it 'should greedily match several segments'301 get('/public/*.*', function(path, ext){302 return 'path: ' + path + ' ext: ' + ext303 })304 get('/public/javascripts/app.js').body.should.eql 'path: javascripts/app ext: js'305 end306 307 it 'should greedily match several segments'308 get('/public/*/*.*', function(dir, path, ext){309 return 'dir: ' + dir + ' path: ' + path + ' ext: ' + ext310 })311 get('/public/javascripts/app.js').body.should.eql 'dir: javascripts path: app ext: js'312 end313 end314 315 describe 'with an unmatchable request path'316 describe 'with "helpful 404" enabled'317 it 'should show the help html'318 enable('helpful 404')319 get('/something').status.should.eql 404320 get('/something').body.should.include('<h1>Express</h1>')321 get('/something').body.should.include('<h2><em>404</em> Not Found</h2>')322 end323 end324 325 describe 'with "helpful 404" disabled'326 it 'should respond with 404 Not Found'327 get('/something').status.should.eql 404328 get('/something').body.should.eql 'Not Found'329 end330 end331 end332 333 describe 'with an exception thrown'334 describe 'with "show exceptions" enabled'335 it 'should show the exception html'336 disable('throw exceptions')337 enable('show exceptions')338 get('/user', function(){339 throw new Error('Access Denied')340 })341 get('/user').status.should.eql 500342 get('/user').body.should.include('<h1>Express</h1>')343 get('/user').body.should.include('<h2><em>500</em> Error: Access Denied</h2>')344 end345 end346 347 describe 'with "show exceptions" disabled'348 it 'should show the regular body'349   disable('throw exceptions')350 disable('show exceptions')351 get('/user', function(){352 throw new Error('Access Denied')353 })354 get('/user').status.should.eql 500355 get('/user').body.should.include('Internal Server Error')356 end357 end358 359 describe 'with "throw exceptions" enabled'360 it 'should propegate to the global scope'361 enable('throw exceptions')362 get('/user', function(){363 throw new Error('Access Denied')364 })365 -{ get('/user') }.should.throw_error366 end367 end368 369 describe 'with "throw exceptions" disabled'370 it 'should not propegate to the global scope'371 disable('throw exceptions')372 get('/user', function(){373 throw new Error('Access Denied')374 })375 -{ get('/user') }.should.not.throw_error376 end377 end378 end379 380 end381end
deleted:spec/spec.utils.js-104 removed
12describe 'Express'3 before4 utils = require('express/utils')5 end6 7 describe 'escape()'8 it 'should escape html'9 utils.escape('<p>this & that').should.eql '&lt;p&gt;this &amp; that'10 end11 end12 13 describe 'uid()'14 it 'should return a string of random characters'15 utils.uid().should.not.eql utils.uid()16 utils.uid().length.should.be_greater_than 2017 end18 end19 20 describe 'mergeParam()'21 describe 'with empty params'22 it 'should merge the given key and value'23 params = {}24 utils.mergeParam('user[names][firstName]', 'tj', params)25 params.user.names.firstName.should.eql 'tj'26 end27 end28 29 describe 'with populated params'30 it 'should merge not overwrite'31 params = { user: { name: 'tj' }}32 utils.mergeParam('user[email]', 'tj@vision-media.ca', params)33 params.user.name.should.eql 'tj'34 params.user.email.should.eql 'tj@vision-media.ca'35 end36 end37 38 describe 'with an object as value'39 it 'should preserve it'40 params = {}41 utils.mergeParam('images[]', { name: 1 }, params)42 utils.mergeParam('images[]', { name: 2 }, params)43 params.images.should.eql [{ name: 1}, { name: 2 }]44 end45 end46 47 describe 'key[number]'48 it 'should merge correctly'49 params = { images: { one: 'foo.png' }}50 utils.mergeParam('images[0]', 'bar.png', params)51 params.images.one.should.eql 'foo.png'52 params.images[0].should.eql 'bar.png'53 end54 end55 56 describe 'key[]'57 describe 'with a single value'58 it 'should still be an array'59 params = {}60 utils.mergeParam('images[]', '1', params)61 params.images.should.eql ['1']62 end63 end64 65 describe 'with empty params'66 it 'should merge correctly'67 params = {}68 utils.mergeParam('images[]', '1', params)69 utils.mergeParam('images[]', '2', params)70 params.images.should.eql ['1', '2']71 end72 end73 74 describe 'with populated params'75 it 'should convert to an array'76 params = { images: 'foo.png'}77 utils.mergeParam('images[]', '1', params)78 params.images.should.eql ['foo.png', '1']79 end80 end81 82 describe 'with several merges'83 it 'should push values'84 params = {}85 utils.mergeParam('images[]', '1', params)86 utils.mergeParam('images[]', '2', params)87 utils.mergeParam('images[]', '3', params)88 params.images.should.eql ['1', '2', '3']89 end90 end91 92 describe 'when nested'93 it 'should marge correctly'94 params = {}95 utils.mergeParam('user[tj][images][]', '1', params)96 utils.mergeParam('user[tj][images][]', '2', params)97 utils.mergeParam('user[tj][images][]', '3', params)98 params.user.should.eql { tj: { images: ['1', '2', '3'] }}99 end100 end101 end102 103 end104end