Sha256: 38fe7c9dd28440d0f7fbbc497e7da534ad8aecd6da7a2e99e203e512292e9e90

Contents?: true

Size: 1.83 KB

Versions: 3

Compression:

Stored size: 1.83 KB

Contents

require 'rack'
require 'webrick'
require 'thread'
require 'stringio'
require 'tap/mechanize/test/mock_server'
require 'tap/mechanize/test/echo_server'

module Tap
  module Mechanize
    
    # 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
    #
    module Test
      
      # 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.
      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
      
      # 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.
      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
    end
  end
end



Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
tap-mechanize-0.5.0 lib/tap/mechanize/test.rb
tap-mechanize-0.5.1 lib/tap/mechanize/test.rb
tap-mechanize-0.6.0 lib/tap/mechanize/test.rb