Testing Ruby system shell calls using Mock objects

Written by Keith McDonnell. Last updated on Thursday, April 01, 2010.


You want to test Ruby code which calls shell commands, e.g.

  Kernel.system "ls -l"
  `df -f`
  %x( du -sh ) 


Use mock object expectations to test that the method was called with the correct arguments.

  def list_files
*  Kernel.system "ls -l"
  require 'test/unit'
  require 'mocha'
  class FileListingTestCase < Test::Unit::TestCase
*  def test_file_listing
*    Kernel.expects(:system).with "ls -l"
*    list_files
*  end

Unfortunately, I havn’t been able to find a way to test the backtick `ls -l` or macro %x( ls -l ) with mocks.┬áSo you must use Kernel.system which isn’t as pretty as the backtick or macro options.

Further reading

If you'd like to discuss this article, you can send me an email keith@dancingtext.com and/or publish an article online and link back to this page.