Question

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!

Was it helpful?

Solution 2

I'm not sure you need that .with(:file) part, try dropping it altogether. Also, I believe by specifying it that way you are literally telling it to expect someone to call that method and pass it a :file symbol rather than e.g. a string filename. Also consider preloading the test YAML file and just returning that:

let(:file_like_object) { double("file like object") }

File.stub(:open).and_return(file_like_object)

OTHER TIPS

The new syntax for stubs looks like this:

allow(File).to receive(:open).with('file_name').and_return(file_like_object)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top