Mock system call in ruby Mock system call in ruby ruby ruby

Mock system call in ruby


%x{…} is Ruby built-in syntax that will actually call Kernel method Backtick (`). So you can redefine that method. As backtick method returns the standard output of running cmd in a subshell, your redefined method should return something similar to that ,for example, a string.

module Kernel    def `(cmd)        "call #{cmd}"    endendputs %x(ls)puts `ls`# output# call ls# call ls


Using Mocha, if you want to mock to following class:

class Test  def method_under_test    system "echo 'Hello World!"    `ls -l`  endend

your test would look something like:

def test_method_under_test  Test.any_instance.expects(:system).with("echo 'Hello World!'").returns('Hello World!').once  Test.any_instance.expects(:`).with("ls -l").onceend

This works because every object inherits methods like system and ` from the Kernel object.


I don't know of a way to mock a module, I'm afraid. With Mocha at least, Kernel.expects doesn't help. You could always wrap the calling in a class and mock that, something like this:

require 'test/unit'require 'mocha'class SystemCaller  def self.call(cmd)    system cmd  endendclass TestMockingSystem < Test::Unit::TestCase  def test_mocked_out_system_call    SystemCaller.expects(:call).with('dir')    SystemCaller.call "dir"  endend

which gives me what I'd hope for:

Started.Finished in 0.0 seconds.1 tests, 1 assertions, 0 failures, 0 errors