Testing invocation of external executables, %x{}, `

July 9, 2009
By David Palm at
Testing invocation of external executables, %x{}, `

If you ever found yourself trying to write tests for code that invokes an external executable, such as:class Beef < ActiveRecord::Base def diskspace(flags = 'sh') `du -#{flags} .`.split.first end end...and wondered how to write a spec that ensures the du command is called with the right options, you might have tried something like:before do @beef = Beef.new endit "has diskspace with humanized multipliers" do Kernel.should_receive(:`).with("du -h .") @beef.diskspace('h') endThat doesn't work.After some headscratching and calls for help on the ruby-talk mailing list, I learned how the Kernel#` method is not being called directly. The Ruby object hierarchy has Object at the top-level, and thus all your objects eventually descends from Object. As Object mixes in Kernel, all your objects have all the methods defined in that module, so it's not Kernel that receives your call to "`", but it's the current 'self'. In the example above it's the @beef instance.Consider:class Sheep def mytick(arg) puts "tickety-tick: #{arg.inspect}" end ...
Read more »

    blog comments powered by Disqus