Permalink
Browse files

Added FakeWeb.with_allow_net_connect_set_to method. This allows you t…

…o temporarily change the value of allow_net_connect for the duration of the provided block.
  • Loading branch information...
1 parent 9eba6f6 commit 9d82439aba4eb64b22273f70c73415131f71904b @myronmarston committed Mar 22, 2010
Showing with 53 additions and 0 deletions.
  1. +24 −0 lib/fake_web.rb
  2. +29 −0 test/test_allow_net_connect.rb
View
@@ -47,6 +47,30 @@ def self.allow_net_connect?
@allow_net_connect
end
+ # call-seq:
+ # FakeWeb.with_allow_net_connect_set_to(true) do
+ # # do something that needs allow_net_connect to be true
+ # end
+ #
+ # or
+ #
+ # FakeWeb.with_allow_net_connect_set_to(false) do
+ # # do something that needs allow_net_connect to be false
+ # end
+ #
+ # Temporarily sets allow_net_connect to the provided value for the duration
+ # of the provided block. When the block completes, it is reverted to whatever
+ # it was before being this method was called.
+ def self.with_allow_net_connect_set_to(value)
+ original_value = FakeWeb.allow_net_connect?
+ FakeWeb.allow_net_connect = value
+ begin
+ yield
+ ensure
+ FakeWeb.allow_net_connect = original_value
+ end
+ end
+
# This exception is raised if you set <tt>FakeWeb.allow_net_connect =
# false</tt> and subsequently try to make a request to a URI you haven't
# stubbed.
@@ -70,6 +70,35 @@ def test_question_mark_method_returns_false_after_setting_allow_net_connect_to_f
assert !FakeWeb.allow_net_connect?
end
+ def test_with_allow_net_connect_set_to_sets_allow_net_connect_for_the_duration_of_the_block_to_the_provided_value
+ [true, false].each do |expected|
+ yielded_value = :not_set
+ FakeWeb.with_allow_net_connect_set_to(expected) { yielded_value = FakeWeb.allow_net_connect? }
+ assert_equal expected, yielded_value
+ end
+ end
+
+ def test_with_allow_net_connect_set_to_returns_the_value_returned_by_the_block
+ assert_equal :return_value, FakeWeb.with_allow_net_connect_set_to(true) { :return_value }
+ end
+
+ def test_with_allow_net_connect_to_reverts_allow_net_connect_when_the_block_completes
+ [true, false].each do |expected|
+ FakeWeb.allow_net_connect = expected
+ FakeWeb.with_allow_net_connect_set_to(true) { }
+ assert_equal expected, FakeWeb.allow_net_connect?
+ end
+ end
+
+ def test_reverts_allow_net_connect_when_the_block_completes_even_if_an_error_is_raised
+ [true, false].each do |expected|
+ FakeWeb.allow_net_connect = expected
+ assert_raise RuntimeError do
+ FakeWeb.with_allow_net_connect_set_to(true) { raise RuntimeError }
+ end
+ assert_equal expected, FakeWeb.allow_net_connect?
+ end
+ end
end

0 comments on commit 9d82439

Please sign in to comment.