title: Mock a `puts` to a file in Rspec
body: <p>I have a silly "queue-class[1]" with the following method, that I want to spec out with Rspec. I am not interested in testing if writing to the file-system works (It works, my computer works) but in whether or not the correct data gets written away. </p>
  
  <pre><code>def write transaction
    File.open("messages/#{@next_id}", "w") {|f| f.puts transaction }
    @next_id += 1
  end
  </code></pre>
  
  <p>The spec for testing this is:</p>
  
  <pre><code>describe TransactionQueue do
    context "#write" do
      it "should write positive values" do
        open_file = mock File
        open_file.stub(:puts)
  
        File.any_instance.stub(:open).and_yield(open_file)
        File.any_instance.should_receive(:open)
        open_file.should_receive(:puts).with("+100")
  
        @queue = TransactionQueue.new
        @queue.write("+100")
      end
    end
  end
  </code></pre>
  
  <p>Running this, fails, because my Mocks never receive the expected "open" and "puts" messages. </p>
  
  <p>Can I mock <code>File</code> this way? Did I use the <code>any_instance</code> correctly; is my attempt to stub a "block-yield" correct?</p>
  
  <p>I'd rather not use extra gems like FakeFS when it can be avoided; this is not so much about getting it to work; bu mostly about actually understanding what is going on. Hence my attempt to avoid extra gems/layers of complexity.</p>
  
  <p>[1] Class is from <a href="http://pragprog.com/book/hwcuc/the-cucumber-book" rel="nofollow">The Cucumber Book</a>; but these tests have littel to do with Cucumber itself. I somehow broke the code when following the book; and want to find out what, by writing unit-tests for the parts that the book does not write tests for: the helper classes.</p>