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)
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
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?
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.