Skip to content

Instantly share code, notes, and snippets.

@timlinquist
Forked from steveburkett/gist:3659891
Created September 6, 2012 21:08
Show Gist options
  • Save timlinquist/3660384 to your computer and use it in GitHub Desktop.
Save timlinquist/3660384 to your computer and use it in GitHub Desktop.
testing ensure
class TolerantFetcher
def self.get(url)
TimeoutNinja.try do
timeout(20) do
begin
handle = open(url)
response = handle.read
ensure
handle.try(:close!) ####### HERE
end
log_response(url, response) if debugging_enabled?
response
end
end
end
require 'spec_helper'
describe TolerantFetcher, :suppress_timeout_ninja_delay do
let(:response) { "Response Text" }
let(:handle) { double(read: "Response Text") }
subject { TolerantFetcher.get("example.com") }
before { handle.stub(:close!) }
describe ".get" do
context "when debugging is disabled" do
before { TolerantFetcher.stub(debugging_enabled?: false) }
context "when the open call returns a response" do
before do
TolerantFetcher.stub(open: handle)
end
it "does not attempt to log the response" do
TolerantFetcher.should_not_receive(:log_response).with(:anything)
end
it "should receive a close!" do
handle.should_receive(:close!)
subject
end
it "calls open with the passed-in URL and a timeout" do
TolerantFetcher
.should_receive(:open)
.with("example.com")
.and_return(handle)
subject
end
it "returns the response" do
subject.should == "Response Text"
end
context "when the read raises exception" do
before do
handle.stub(:read).and_raise(Exception)
end
it "should call close!" do
handle.should_receive(:close!)
subject.as_null_object
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment