绕过规范中的初始化程序
我有以下方法来创建新的 Connection 对象。它将打开一个串行端口。注意,当端口不存在时会失败。
class Connection
def initialize(port)
begin
@serial = SerialPort.new(port, 9600, 8, 1, SerialPort::NONE)
rescue
exit(1)
end
end
def send_command
@serial.write "Something"
end
end
我为此方法编写了 RSpec 规范,到目前为止一切顺利。现在,我想指定下一个方法“send_command”。
问题是我无法在此规范中调用 Connection.new("/some/port")
因为它会失败(端口不存在)。如何绕过创建方法而不存根新方法?如果我理解正确的话,我不允许存根或模拟我正在测试的课程,对吧?
谢谢!
I have the following method to create a new Connection object. It will open a serial port. Note that it will fail when the port does not exist.
class Connection
def initialize(port)
begin
@serial = SerialPort.new(port, 9600, 8, 1, SerialPort::NONE)
rescue
exit(1)
end
end
def send_command
@serial.write "Something"
end
end
I wrote a RSpec spec for this method, so far so good. Now, I would like to spec the next method, "send_command".
The problem is I can not call Connection.new("/some/port")
in this spec as it will fail (the port does not exist). How can I bypass the creation method without stubbing the new method? If I understand correctly I am not allowed to stub or mock the class I'm testing, right?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以传入 SerialPort 对象而不是端口号(依赖注入),或具有返回 SerialPort 对象的 create 方法的工厂对象(抽象工厂模式)。然后测试可以在假/模拟/虚拟串行端口或串行端口工厂中通过。
但也许这就是我所说的 C++ 程序员,gnab 的建议似乎更 Rubyish...
You could pass in a SerialPort object instead of a port number (dependency injection), or a factory object that has a create method that returns a SerialPort object (abstract factory pattern). The tests could then pass in a fake/mock/dummy SerialPort or SerialPort factory.
But maybe that is the C++ programmer in me talking, gnab's advice seems to be more Rubyish...
您可以对
SerialPort
类的new
和write
方法进行存根处理。You could stub the
new
andwrite
methods of theSerialPort
class.这有点 hacky,但您可以调用
Connection.allocate
,而不是调用Connection.new
。这将创建一个对象而不调用initialize
。This is somewhat hacky, but rather than calling
Connection.new
, you could callConnection.allocate
. This creates an object without callinginitialize
.