Skip to content

Commit 7c675a0

Browse files
committed
Add ability to stop MockServer again
This is useful when using MockServer in different test files and you are running the full suite.
1 parent ba97239 commit 7c675a0

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

lib/mock_server.rb

+21
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,14 @@ def start
2323
self
2424
end
2525

26+
def stop
27+
Rack::Handler::WEBrick.shutdown
28+
29+
wait_for_shutdown("0.0.0.0", @port)
30+
31+
self
32+
end
33+
2634
module Methods
2735
def mock_server(*args, &block)
2836
app = Class.new(Sinatra::Base)
@@ -45,6 +53,7 @@ def listening?(host, port)
4553
socket.close unless socket.nil?
4654
true
4755
rescue Errno::ECONNREFUSED,
56+
Errno::ECONNRESET,
4857
Errno::EBADF, # Windows
4958
Errno::EADDRNOTAVAIL # Windows
5059
false
@@ -62,4 +71,16 @@ def wait_for_service(host, port, timeout = 5)
6271

6372
true
6473
end
74+
75+
def wait_for_shutdown(host, port, timeout = 5)
76+
start_time = Time.now
77+
78+
until !listening?(host, port)
79+
if timeout && (Time.now > (start_time + timeout))
80+
raise SocketError.new("Socket did not close within #{timeout} seconds")
81+
end
82+
end
83+
84+
true
85+
end
6586
end

test/mock_server_test.rb

+17
Original file line numberDiff line numberDiff line change
@@ -50,3 +50,20 @@ def test_server
5050
assert_equal "Goodbye", open("http://localhost:4002").read
5151
end
5252
end
53+
54+
class MockServerStopTest < Test::Unit::TestCase
55+
def setup
56+
@server = MockServer.new(HelloWorldSinatra, 4003)
57+
@server.start
58+
end
59+
60+
def test_stop_server
61+
assert_equal "Hello", open("http://localhost:4003").read
62+
63+
@server.stop
64+
65+
assert_raises(Errno::ECONNREFUSED) {
66+
open("http://localhost:4003").read
67+
}
68+
end
69+
end

0 commit comments

Comments
 (0)