RSpec: how to test file operations and file content

后端 未结 5 740
心在旅途
心在旅途 2020-12-24 00:40

In my app, I have the following code:

File.open "filename", "w" do |file|
  file.write("text")
end

I want to te

5条回答
  •  囚心锁ツ
    2020-12-24 01:28

    I would suggest using StringIO for this and making sure your SUT accepts a stream to write to instead of a filename. That way, different files or outputs can be used (more reusable), including the string IO (good for testing)

    So in your test code (assuming your SUT instance is sutObject and the serializer is named writeStuffTo:

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

    String IO behaves like an open file. So if the code already can work with a File object, it will work with StringIO.

提交回复
热议问题