Module: Tap::Mechanize::Test

Defined in:
lib/tap/mechanize/test.rb,
lib/tap/mechanize/test/echo_server.rb,
lib/tap/mechanize/test/mock_server.rb

Overview

Mechanize::Test allows you to mock out remote servers to test HTTP clients. The mechanize_test method launches a WEBrick server hosting a Rack application for the duration of the block. Typically the application is constructed to send back an expected response.

class SampleTest < Test::Unit::TestCase
  include Tap::Mechanize::Test

  def test_mechanize_test
    m = MockServer.new {|env| ['success'] }
    a = WWW::Mechanize.new
    mechanize_test(m) do
      assert_equal 'success', a.get('http://localhost:2000/').body
    end
  end
end

Defined Under Namespace

Classes: EchoServer, MockServer

Instance Method Summary collapse

Instance Method Details

#default_webrick_config(log_dev = StringIO.new('')) ⇒ Object

The default WEBRick config for a mechanize_test(. By default the sever runs on port 2000 and logs all data to the input log device.



32
33
34
35
36
37
38
39
# File 'lib/tap/mechanize/test.rb', line 32

def default_webrick_config(log_dev=StringIO.new(''))
  common_logger = WEBrick::Log.new(log_dev, WEBrick::Log.const_get(:WARN) )
  {
    :Port => 2000,
    :Logger => common_logger,
    :AccessLog => common_logger
  }
end

#mechanize_test(app = EchoServer, config = default_webrick_config) ⇒ Object

Sets up a local WEBRick server that runs the Rack app and yields to the block. The server runs on its own thread and will be shutdown after the test completes. See default_webrick_config for setup information.



44
45
46
47
48
49
50
51
52
53
# File 'lib/tap/mechanize/test.rb', line 44

def mechanize_test(app=EchoServer, config=default_webrick_config)
  begin
    server = ::WEBrick::HTTPServer.new(config); 
    server.mount("/", Rack::Handler::WEBrick, app); 
    Thread.new { server.start }
    yield
  ensure
    server.shutdown
  end
end