从誓言启动服务器进行testing的正确方法是什么?

我有一个快递服务器,我正在testing使用誓言。 我想从誓言testing套件中运行服务器,所以我不需要在后台运行它,以便testing套件能够工作,然后我可以创build一个运行服务器并在其中进行testing的蛋糕任务隔离。

server.coffee我创build了(express)服务器,configuration它,设置路由并调用app.listen(port)像这样:

 # Express - setup express = require 'express' app = module.exports = express.createServer() # Express - configure and set up routes app.configure -> app.set 'views', etc.... .... # Express - start app.listen 3030 

在我简单的routes-test.js我有:

 vows = require('vows'), assert = require('assert'), server = require('../app/server/server'); // Create a Test Suite vows.describe('routes').addBatch({ 'GET /' : respondsWith(200), 'GET /401' : respondsWith(401), 'GET /403' : respondsWith(403), 'GET /404' : respondsWith(404), 'GET /500' : respondsWith(500), 'GET /501' : respondsWith(501) }).export(module); 

其中respondsWith(code)function类似于誓言文档中的…

当我在上面的testing中require服务器时,它会自动开始运行服务器,testing运行并通过,这很好,但我不觉得我正在做这个“正确”的方式。

我对服务器何时开始没有太多的控制,如果我想将服务器configuration为指向“testing”环境而不是默认环境,或者在进行imtesting时更改默认日志logging级别,会发生什么情况?

PS我要把我的誓言转换成Coffeescript,但现在它的所有在JS,即时在学习模式从文档!

这是一个有趣的问题,因为昨天晚上我做了你想做的事情。 我有一个小巧的CoffeScript Node.js应用程序,碰巧就像你所展示的一样。 然后,我重构它,创build下面的app.coffee

 # ... Imports app = express.createServer() # Create a helper function exports.start = (options={port:3000, logfile:undefined})-> # A function defined in another module which configures the app conf.configure app, options app.get '/', index.get # ... Other routes console.log 'Starting...' app.listen options.port 

现在我有一个index.coffee (相当于你的server.coffee ),就像下面这样简单:

 require('./app').start port:3000 

然后,我用Jasmine-node和Zombie.js写了一些testing。 testing框架是不同的,但原理是一样的:

 app = require('../../app') # ... # To avoid annoying logging during tests logfile = require('fs').createWriteStream 'extravagant-zombie.log' # Use the helper function to start the app app.start port: 3000, logfile: logfile describe "GET '/'", -> it "should have no blog if no one was registered", -> zombie.visit 'http://localhost:3000', (err, browser, status) -> expect(browser.text 'title').toEqual 'My Title' asyncSpecDone() asyncSpecWait() 

重点是:我所做的,我会build议在一个启动服务器的模块中创build一个函数。 然后,在任何你想要的地方调用这个函数。 我不知道这是不是“好的devise”,但它工作,似乎对我来说是可读性和实用性。

另外,我怀疑Node.js和CoffeScript中没有“好devise”。 那些是全新的,非常创新的技术。 当然,我们也可以“觉得有什么不对劲” – 就像这种情况,两个不同的人不喜欢devise并改变它。 我们可以感受到“错误的方式”,但这并不意味着已经有了“正确的方式”。 总结起来,我相信我们将不得不在发展中发明一些“正确的方法”:)

(但是也可以问一些好的做法,也许有人有一个好主意,公开讨论会对其他开发者有帮助。)