RSpec: how to test file operations and file content

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

    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
    

提交回复
热议问题