Rspec -- need to stub File.open that gets called in another file

Shail Patel picture Shail Patel · Jun 6, 2013 · Viewed 14k times · Source

In my test I'm initializing a new class called Package with some parameters.

In the initialization of this class, I open a file that is available on my remote boxes but not something that is commonly there locally. I was wondering how I would go about stubbing that method in my test.

I'm using rspec and mocha. I tried something like:

File.stubs(:open).with(:file).returns(File.open("#{package_root}/test_files/test.yml"))

I had this line before I initialized Package in my test.

I got this error:

unexpected invocation: File.open('package/test_files/test.yml')
   satisfied expectations:
   - allowed any number of times, not yet invoked: File.open(:file)

I'm not that familiar with rspec or mocha, so help is appreciated. Thanks!

Answer

Chris McKenzie picture Chris McKenzie · Nov 24, 2014

The new syntax for stubs looks like this:

allow(File).to receive(:open).with('file_name').and_return(file_like_object)