Weird behavior of mocking ruby class methods

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‘asd.txt’)
describe FileReader, “do_read” do
it “should throw File Not Found on non-existent file” do
reader =
lambda {
}.should raise_error(Errno::ENOENT)
describe FileReader, “do_read” do
it “should read the mock contents” do
reader =
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
“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
mocking erased the “read” method. (Please see the output in “Scenario 2”
the attached file) 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:
Sent from the rspec-users mailing list archive at

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs