weird behavior of mocking ruby class methods

View: New views
1 Messages — Rating Filter:   Alert me  

weird behavior of mocking ruby class methods

by Shaker :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Hello everyone:
  After I played with Rspec for three months, I realized a weird behavior of mocking ruby classes (e.g. File).
  Please let me post a sample code before I point out the problems:
  #file_reader.rb (to be tested)
  class FileReader
    def do_read
      File.read('asd.txt')
    end
  end
  #file_reader_spec.rb
  describe FileReader, "do_read" do
    it "should throw File Not Found on non-existent file" do
      reader = FileReader.new()
      lambda {
        reader.do_read
      }.should raise_error(Errno::ENOENT)
    end
  end
  describe FileReader, "do_read" do
    it "should read the mock contents" do
      reader = FileReader.new()
      File.should_receive(:read).and_return('file contents')
      reader.do_read.should == 'file contents'
    end
  end
In the test cases shown above, I wanted to mock the "read" method in ruby "File" class.
The first case passed while the second one failed. I suspected that the mocking was not working in the second case. (Please see the output in "Scenario 1" in the attached file)
Then I switched the running order of the test cases, another interesting result came out. The mocking worked well this time but "read" method in "File" class became undefined in the second test case. It seemed that the mocking erased the "read" method. (Please see the output in "Scenario 2" in the attached file)
result.txt
I am wondering what is going on out there when I mocked a method of ruby class?
Do I use mocking in a proper way as the sample code shown above?
What is the correct way of mocking methods of ruby classes?