Srikanth Gurram Srikanth Gurram - 25 days ago 9
Ruby Question

How to mock a method that is outside of a class in Rspec?

I have to mock a method which is not associated with any class. Could someone help me?

It's something like this:

#device.rb
require_relative 'common'
class Device

def connect_target(target)
status = connect(target)
return status
end

end

#common.rb
def connect(target)
puts "connecting to target device"
end


I have to write unit tests for the "connect_target" in device class
by mocking the external methods from common.rb

Answer

I have to mock a method which is not associated with any class.

There is no such thing as a method not associated with any module. There is exactly one kind of method in Ruby: instance methods of modules (or classes, which are modules).

connect is defined as a private instance method of Object.

You would mock it something like this:

allow(some_device).to receive(:connect)

Note that it doesn't even matter anyway, where the method is defined: there is no mention of either Device or Object here.