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!
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…