In my app I have such code:
File.open "filename", "w" do |file|
file.write("text")
end
I want to test this code via rspec. What is the best practices for doing this?
In my app I have such code:
File.open "filename", "w" do |file|
file.write("text")
end
I want to test this code via rspec. What is the best practices for doing this?
For someone like me who need to modify multiple files in multiple directories (e.g. generator for Rails), I use temp folder.
This is how to mock File (with rspec 3.4), so you could write to a buffer and check its content later:
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 namedwriteStuffTo
:String IO behaves like an open file. So if the code already can work with a File object, it will work with StringIO.
You can use fakefs.
It stubs filesystem and creates files in memory
You check with
if file was created.
You can also just read it with
and run expectation on its contents.
For very simple i/o, you can just mock File. So, given:
then:
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.