使用RSpec模拟TCPSocket [英] Mock TCPSocket with RSpec

查看:101
本文介绍了使用RSpec模拟TCPSocket的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图围绕大量使用TCPSockets(具体来说是IRC bot)的应用程序编写测试.在编写第一堂课的测试时,我一直在这样做:

I'm attempting to write tests around an application that makes heavy use of TCPSockets (an IRC bot to be specific). While writing my first class's tests, I had been skimping by with doing:

#In the describe block
before(:all) { TCPServer.new 6667 }

...这允许我的TCPSockets运行(通过连接到localhost:6667),尽管实际上并没有对其进行正确的模拟.但是,由于无法在同一端口上创建TCPServer,因此现在进入第二类时会引起问题.

...which allowed for my TCPSockets to function (by connecting to localhost:6667), though they are not actually being properly mocked. However, this has now caused problems when moving onto my second class as I cannot create a TCPServer on the same port.

如何模拟TCPSocket类,使我能够测试诸如its(:socket) { should be_kind_of(TCPSocket) }之类的东西以及诸如#readline和#write之类的其他常见操作?

How can I mock the TCPSocket class in such a way that will allow me to test things such as its(:socket) { should be_kind_of(TCPSocket) } and other common operations like #readline and #write?

推荐答案

您可以尝试在之前之后跟踪并关闭TCPServer:

You could try keeping track and closing the TCPServer in your before and after:

before do
  @server = TCPServer.new 6667
end

after do
  @server.close
end

it ... do
end

it ... do
end

在每个单独的测试之后,TCPServer被杀死,因此您可以使用相同的端口创建一个新的服务器.

After each of the individual tests, the TCPServer is killed so you can create a new one with the same port.

这篇关于使用RSpec模拟TCPSocket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆