RSpec and Open-URI, how can I poke fun at creating a SocketError / TimeoutError

I want to be able to indicate that when Open-Uri open () either calls a timeout or throws an exception such as a SocketError, I handle things as expected, however I am having problems with this.

Here is my spec (for SocketError):

@obj.should_receive(:open).with("some_url").and_raise(SocketError) 

And the part of my object where I use open-uri:

 begin resp = open(url) resp = resp.read rescue SocketError something = true end 

However, in this situation, the specification does not work, as with the nil.read error.

This is the second time this week that I encountered this problem, in the previous time I tried to simulate a TimeoutError when wrapping open() with timeout() {} , while I gave up and just called the actual timeout to happen by opening class. I obviously could get this to throw a SocketError by trying to raise an invalid url, but I'm sure there is a proper way to mock this with RSpec.

Update: I obviously did not think clearly that late at night, the error was actually when I re-tried the URL after the SocketError, and_raise (SocketError) part was working fine.

+4
source share
1 answer

The line you provided should work based on the information you provided: I made a tiny test class and specification (see below) with only the functions described, and everything worked out as expected. Perhaps it would be helpful if you could provide a little more context - for example, the full "it" block from the specification could cause some other problems.

As already mentioned, the following spec passes, and I believe that it captures the logic you tried to verify:

 require 'rubygems' require 'spec' class Foo attr_accessor :socket_error def get(url) @socket_error = false begin resp = open(url) resp = resp.read rescue SocketError @socket_error = true end end end describe Foo do before do @foo = Foo.new end it "should handle socket errors" do @foo.should_receive(:open).with("http://www.google.com").and_raise(SocketError) @foo.get("http://www.google.com") @foo.socket_error.should be_true end end 
+2
source

All Articles