【发布时间】:2019-09-25 20:50:32
【问题描述】:
我正在为我的 Hubot(充当 Slack 机器人)编写测试。由某些 Slack 消息触发,机器人将 HTTP POST 请求发送到单独的 Rails 应用程序。如何检查我的测试脚本是否已发送 HTTP 请求?我的猜测是我应该检查robot.logger 的内容(如果有更好的方法,请告诉我) - 但如果是这样,我怎样才能访问测试中的日志?
Hubot 脚本(基本上,它会通知 Rails 应用有关用户离开办公室休息的信息):
module.exports = (robot) ->
robot.respond /off to lunch/i, (res) ->
res.reply('Later alligator')
robot.logger.info "This user is going on lunch break: #{res.message.user.id}"
data = JSON.stringify({
slack_user_id: res.message.user.id
})
robot.http(process.env.RAILS_APP_URL + '/break')
.header('Content-Type', 'application/json')
.post(data) (err, resp, body) ->
if err
robot.logger.info "Encountered an error. #{err}"
res.reply('Sorry, there was an error recording your break time')
else
robot.logger.info 'Successfully sent HTTP POST request to Rails app'
执行此脚本时的日志输出:
INFO This user is going on lunch break: [SLACK_USER_ID]
INFO Successfully sent HTTP POST request to Rails app
如上所述,我想通过断言日志将包含消息 'Successfully sent HTTP POST request to Rails app' 来检查我的测试脚本是否发送了 HTTP 请求。但是,我不知道如何在我的测试中访问 Hubot 的日志。我认为这与process.stdout 有关,因为机器人记录到标准输出,但我无法让它工作。
测试脚本:
Helper = require('hubot-test-helper')
helper = new Helper('../scripts/break-start.coffee')
request = require('request')
expect = require('chai').expect
nock = require('nock')
describe 'bot responds to user message and sends ', ->
beforeEach ->
# Set up the room before running the test.
@room = helper.createRoom()
# Set up a request interceptor.
nock(process.env.RAILS_APP_URL)
.post('/break', { slack_user_id: 'bob' })
.reply(200)
afterEach ->
# Tear down the room after the test to free up the listener.
@room.destroy()
context 'user sends lunch message', ->
beforeEach ->
@room.user.say('bob', '@hubot Off to lunch')
it 'responds to users who are off to lunch', ->
expect(@room.messages).to.eql [
['bob', '@hubot Off to lunch']
['hubot', '@bob Later alligator']
# I want to do something like this:
# expect(robot.log).include('Successfully sent HTTP POST request to Rails app')
当然,当我运行测试时,我可以在控制台日志中看到正在发送 HTTP 请求,但我还想断言它,以便在未发送请求时测试失败。
执行测试时的日志输出:
INFO This user is going on lunch break: bob
✓ responds to users who are off to lunch
INFO Successfully sent HTTP POST request to Rails app
提前感谢您的帮助。
【问题讨论】:
标签: testing logging coffeescript mocha.js hubot