title: How do you unit test code that generates or uses shell commands?
body: <p>I'm writing a Ruby library that will automate some shell commands. The commands will depend on quite a complex set of business logic.</p>
  
  <p>I want to unit test the code that generates those shell commands. I'm not sure how would I do that; I don't care much about the exact text of the commands, but I want to make sure the commands are affected by logic - which is of course the purpose of the unit tests.</p>
  
  <p>My current idea is to encapsulate the command generation into very thin template-like objects (or just templates), and have logic code call those objects when it needs to produce a shell command, and then I can check that logic code calls expected methods on the template code. This still leaves the template code untested, but that's not as important as verifying the logic. Basically</p>
  
  <pre><code>class DirectoryMaker
    def initialize(generator)
      @generator = generator
    end
    def make_directory(name)
      if name=='baz'
        raise 'YOURE NOT ALLOWED TO DO THAT'
      else
        @generator.mkdir(name)
      end
    end
  end
  
  describe DirectoryMaker do
    it 'should produce a mkdir command' do 
      generator = double('Generator')
      generator.should_receive('mkdir').with('foo').and_return('')
  
      described_class.new(generator).make_directory('foo')
    end
  
    it 'should raise an exception when passed baz as a name' do
      expect {
        described_class.new(double('Generator')).make_directory('baz')
      }.to raise_error
    end
  end
  </code></pre>
  
  <p>Ah, it seems I've answered my question, but if you have better suggestions I'd be happy to hear them.</p>