This needs tests but can I get your opinion? Optionally autolaunch a visual diff tool for comparing registered stubs #137

Closed
wants to merge 1 commit into
from
View
4 lib/webmock/errors.rb
@@ -1,7 +1,8 @@
module WebMock
-
class NetConnectNotAllowedError < StandardError
def initialize(request_signature)
+ RegisteredStubDiffer.new(request_signature.body) if ENV['show_visual_diffs_for_webmock']
+
text = "Real HTTP connections are disabled. Unregistered request: #{request_signature}"
text << "\n\n"
text << stubbing_instructions(request_signature)
@@ -29,5 +30,4 @@ def stubbing_instructions(request_signature)
text
end
end
-
end
View
55 lib/webmock/register_stub_differ.rb
@@ -0,0 +1,55 @@
+module WebMock
+ class RegisteredStubDiffer
+ def initialize body
+ if body
+ Dir.mkdir_p stub_directory
+
+ save_attempted_file body
+
+ registered = save_registered_stubs
+ registered.each { |r| diff r }
+
+ cleanup registered
+ end
+ end
+
+ private
+
+ def diff registered
+ `#{diff_tool} #{registered} #{attempted_file}`
+ end
+
+ def attempted_file
+ attempted = File.join stub_directory, "attempted_stub.txt"
+ end
+
+ def stub_directory
+ File.join %w(tmp webmock)
+ end
+
+ def cleanup files
+ File.delete attempted, *files
+ end
+
+ def save_attempted_file body
+ File.open(attempted, "w") { |f| f << body }
+ end
+
+ def save_registered_stubs
+ WebMock::StubRegistry.instance.request_stubs.map.
+ each_with_index do |stub, index|
+ file = "tmp/webmock/registered_stub_#{index}"
+
+ File.open file, "w" do |f|
+ f << stub.request_pattern.body_pattern
+ end
+
+ file
+ end
+ end
+
+ def diff_tool
+ ENV['diff_tool'] || "opendiff"
+ end
+ end
+end
View
4 spec/unit/registered_stub_differ_spec.rb
@@ -0,0 +1,4 @@
+require File.expand_path('spec/spec_helper')
+
+describe WebMock::RegisteredStubDiffer do
+end