Search code examples
ruby-on-railsrspecstringio

What is `StringIO` in the context of RSpec testing (Ruby on Rails)?


What is StringIO in Ruby on Rails?

I'm trying to understand another SO answer that references StringIO, but its over my head.

I would suggest using StringIO for this and making sure your SUT accepts a stream to write to instead of a filename.

testIO = StringIO.new
sutObject.writeStuffTo testIO 
testIO.string.should == "Hello, world!"

Source: Rspec: how to test file operations and file content

Ruby-doc.org

Pseudo I/O on String object.

Source: http://ruby-doc.org/stdlib-1.9.3/libdoc/stringio/rdoc/StringIO.html)

Robots.thoughtbot

This is common in tests where we might inject a StringIO instead of reading an actual file from disk.

Source: https://robots.thoughtbot.com/io-in-ruby#stringio

My case:

File.open("data.dat", "wb") {|f| f.write(snapshot)}

In my application I want to test the above, but I'm still confused how StringIO applies to implementing an RSpec test.

Could anyone with some experience in StringIO give some guidance?


Solution

  • StringIO is a string-based replacement for an IO object. It acts same as a file, but it's kept in memory as a String.

    In your case I don't think it's really applicable. At least not with your current code. That's because you have File.open call that creates an IO object and immediately does something with it.

    If for example you had something like this:

    def write_data(f)
      f.write(snapshot)
    end
    
    # your code would be
    f = File.open("data.dat", "wb")
    write_data(f)
    
    # test would be
    testIO = StringIO.new
    write_data(testIO)
    testIO.string.should == "Hello, world!"