Create a gist now

Instantly share code, notes, and snippets.

Net:HTTP tutorial #2: simple HTTPServer - useful to test your pages/api calls and to play with plain http
# simple HTTPServer:
# useful to test your pages/api calls!
class HTTPServer
def initialize(port, body)
require 'socket'
@server = Thread.new do
server = TCPServer.open port
loop do
client = server.accept
content_type = "text/html"
client.puts "HTTP/1.1 200/OK\nContent-type:#{content_type}\n\n#{body}\n\n"
client.close
end
end
end
def kill!
@server.kill
end
alias :kill :kill!
end
# vanilla ruby and rspec example, uncomment and run:
# srv = HTTPServer.new 2000, "hello world"
# require 'net/http'
# uri = URI.parse "http://localhost:2000"
# page = Net::HTTP.get_response uri
# puts "page should =~ /hello world/ (uncomment the line below)"
# # page.should =~ /hello world/
# srv.kill
# full fledged spec, adding nokogiri:
# remember to remove the "require 'spec_helper'" line for faster load time
# require 'net/http'
#
# class YourService
# def self.get
# uri = URI.parse "http://localhost:2000"
# Net::HTTP.get_response(uri).body
# end
# end
#
# describe "Something" do
# before :all do
# @srv = HTTPServer.new 2000, "<div>hello world</div>"
# end
#
# after :all do
# @srv.kill
# end
#
# it "should greet" do
# page = YourService.get
# page.should =~ /hello world/
# end
#
# it "should greet" do
# require 'nokogiri'
# page = Nokogiri::HTML YourService.get
# page.css("div").inner_text.should == "hello world"
# end
# end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment