misterinevitable

Strings as IO objects

You can use the StringIO class to create IO objects which are backed by an in-memory string.

One use case for this is unit-testing where you need to attach a file using ActiveStorage. One of the ways you can attach data to the record is by supplying the attach method with an io object. Using StringIO.new you can create an io object using a string.

invoice.hardcopy.attach(io: StringIO.new("Services: $200"),
                        filename: "invoice.txt",
                        content_type: "txt")

Using this technique, you can avoid creating and accessing a file on disk, which would slow down your test.