RSpec: how to test file operations and file content

后端 未结 5 766
心在旅途
心在旅途 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:19

    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.

提交回复
热议问题