title: Issue with testing Tempfile in ruby
body: <p>I have a block of code that creates Tempfiles</p>
  
  <pre><code>@tmp_file = Tempfile.new("filename")
  </code></pre>
  
  <p>I keep them closed after creation,</p>
  
  <pre><code>@tmp_file.close unless @tmp_file.closed?
  </code></pre>
  
  <p>When there is a need to add data to the temp files I open them and add data as below</p>
  
  <pre><code>   def add_row_to_file(row)
        @tmp_file.open
        @tmp_file.read
        @tmp_file.print(row.to_json + "\n")
      end
  </code></pre>
  
  <p>All is well, but for testing the same I have stubbed tempfile as below and is creating an error when the test case runs into <code>add_row_to_file(row)</code> </p>
  
  <pre><code>  buffers = {}
  
    Tempfile.stub(:new) do |file_name|
      buffer = StringIO.new
      buffers[file_name] = buffer
    end
  </code></pre>
  
  <p>Error message is :</p>
  
  <pre><code>Failure/Error: ]],
   NoMethodError:
     private method `open' called for #&lt;StringIO:0x00000010b867c0&gt;
  </code></pre>
  
  <p>I want to keep the temp files closed on creation as there is a max temp files open issue at OS level (I have to deal with uploading lot of tempfiles to S3)
  but for testing I have a problem accessing the private method of StringIO.</p>
  
  <p>Any idea how to solve this problem? Thanks.</p>
  
  <p>I have a work around, which is to skip closing the StringIO when in test environment.</p>
  
  <pre><code>@tmp_file.close unless @tmp_file.closed? || Rails.env.test?
  </code></pre>
  
  <p>and update <code>add_row_to_file(row)</code> as below</p>
  
  <pre><code>   def add_row_to_file(row)
        @tmp_file.open unless Rails.env.test?
        @tmp_file.read unless Rails.env.test?
        @tmp_file.print(row.to_json + "\n")
      end
  </code></pre>