how do you stub a that happens inside a block?

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

def write_something'file.txt') do |f|
    return contents =

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

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


You can stub any instance of File:

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

or you can stub 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 ...