Mock system call in ruby

Viewed 8274

Know of a way to mock %[]? I'm writing tests for code that makes a few system calls, for example:

def log(file)
  %x[git log #{file}]
end

and would like to avoid actually executing system calls while testing this method. Ideally I'd like to mock %x[..] and assert that the correct shell command is passed to it.

5 Answers

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

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

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").once
end

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

Related