obaqueiro obaqueiro - 4 months ago 19
Ruby Question

How do I mock or override Kernel.system?

How would be the correct way to mock or override the

Kernel.system
method so that when called with:

system("some command")


instead of executing the command, it executes some predefined code?

I tried adding the following to my Test class:

module Kernel
def system
puts "SYSTEM CALL!!"
end
end


But it did not work as expected, instead, the system call was run when executing a test.

Answer

If you are talking about unit tests and use Rspec, you should be able to do it like this:

Kernel.should_receive(:system)

or a little more loose:

Kernel.stub(:system)

More info: https://www.relishapp.com/rspec/rspec-mocks/v/2-13/docs/message-expectations/expect-a-message