47

In my app, I have the following code:

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

I want to test this code via RSpec. What are the best practices for doing this?

Sajad Torkamani
  • 544
  • 1
  • 7
  • 18
petRUShka
  • 9,812
  • 12
  • 61
  • 95
  • @Wayne I'm wondering how you will proceed with testunit See [this question][1] [1]: http://stackoverflow.com/questions/11619884/testunit-how-to-test-file-operations-and-file-content – netbe Jul 23 '12 at 20:21

5 Answers5

64

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.

pimpin
  • 277
  • 2
  • 13
Danny Staple
  • 7,101
  • 4
  • 43
  • 56
  • 1
    This was an excellent answer. I wish I could upvote you more than once. – Jazzepi Oct 29 '13 at 12:53
  • 2
    Good answer, I know it was not asked but it would have been perfect if It included the partner 'read' example as well. – John Doe Sep 15 '16 at 02:23
  • 1
    How to modify the code to use String.IO? It seems resulting code will be much uglier, just so testing is easier? – Marko Avlijaš Dec 13 '16 at 14:11
  • I've added more info to the answer on what the StringIO class does. You could combine my answer with Wayne's and mock('file') with a wrapper to a StringIO object. – Danny Staple Dec 14 '16 at 14:15
52

For very simple i/o, you can just mock File. So, given:

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

then:

describe "foo" do

  it "should create 'filename' and put 'text' in it" do
    file = mock('file')
    File.should_receive(:open).with("filename", "w").and_yield(file)
    file.should_receive(:write).with("text")
    foo
  end

end

However, this approach falls flat in the presence of multiple reads/writes: simple refactorings which do not change the final state of the file can cause the test to break. In that case (and possibly in any case) you should prefer @Danny Staple's answer.

Wayne Conrad
  • 103,207
  • 26
  • 155
  • 191
22

This is how to mock File (with rspec 3.4), so you could write to a buffer and check its content later:

it 'How to mock File.open for write with rspec 3.4' do
  @buffer = StringIO.new()
  @filename = "somefile.txt"
  @content = "the content fo the file"
  allow(File).to receive(:open).with(@filename,'w').and_yield( @buffer )

  # call the function that writes to the file
  File.open(@filename, 'w') {|f| f.write(@content)}

  # reading the buffer and checking its content.
  expect(@buffer.string).to eq(@content)
end
Eduardo Santana
  • 5,780
  • 3
  • 19
  • 21
19

You can use fakefs.

It stubs filesystem and creates files in memory

You check with

File.exists? "filename" 

if file was created.

You can also just read it with

File.open 

and run expectation on its contents.

mehowte
  • 449
  • 3
  • 6
3

For someone like me who need to modify multiple files in multiple directories (e.g. generator for Rails), I use temp folder.

Dir.mktmpdir do |dir|
  Dir.chdir(dir) do
    # Generate a clean Rails folder
    Rails::Generators::AppGenerator.start ['foo', '--skip-bundle']
    File.open(File.join(dir, 'foo.txt'), 'w') {|f| f.write("write your stuff here") }
    expect(File.exist?(File.join(dir, 'foo.txt'))).to eq(true)
  end
end  
Othmane El Kesri
  • 603
  • 5
  • 16
lulalala
  • 17,572
  • 15
  • 110
  • 169