[rspec-users] weird behavior of mocking ruby class methods

Shaker flyeminent at hotmail.com
Thu Dec 6 21:51:21 EST 2007

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
  describe FileReader, "do_read" do
    it "should throw File Not Found on non-existent file" do
      reader = FileReader.new()
      lambda { 
      }.should raise_error(Errno::ENOENT)
  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'
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)
http://www.nabble.com/file/p14205880/result.txt result.txt 
I am wondering what is going on out there when I mocked a method of ruby
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?
View this message in context: http://www.nabble.com/weird-behavior-of-mocking-ruby-class-methods-tf4959949.html#a14205880
Sent from the rspec-users mailing list archive at Nabble.com.

More information about the rspec-users mailing list