how do you stub a file.read that happens inside a File.open block?

How do I stub a file.read call so that it returns what I want it to? The following does not work.

def write_something
  File.open('file.txt') do |f|
    return contents = f.read
  end
end

# rspec
describe 'stub .read' do
  it 'should work' do
    File.stub(:read) { 'stubbed read' }
    write_something.should == 'stubbed read'
  end
end

It looks like the stub is being applied to the File class and not the file instance inside my block. So File.read returns stubbed read as expected. But when I run my spec it fails.

Answers


You can stub any instance of File:

File.any_instance.stub(:read) { 'stubbed read' }

or you can stub File.open to yield a double:

file = double(File, read: 'stubbed read')
File.stub(:open) { |&block| block.yield file }

As an aside, it might be best to replace 'stubbed read' with a double.


Need Your Help

Hadoop Web Authentication using Kerberos

hadoop distributed distributed-computing cloudera

I configured hadoop using kerberos, everything works fine, I can browse hdfs, submit jobs, etc. But failed http web authentication.

Can't set titleView in the center of navigation bar because back button

ios objective-c uinavigationbar

I'm using an image view to display an image in my nav bar. The problem is that I can't set it to the center correctly because of the back button. I checked the related questions and had almost the ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.