Running a web server inside ruby ​​tests

I am writing a library to wrap tsung functionality in a way that can be better used by rails applications. I want to write some integration tests, which boil down to the following:

  • starting a simple web server
  • run tsung-recorder through the library
  • run selenium, with a firefox profile configured to use the tsung proxy server, and get this page from the server launched in step 1
  • Browse through the recorded library (it exists, it is in the right place, etc.).

For step 1, although I can run the vanilla rail application from the outside (for example, %x{rails s} ), I am sure that there is a better way to programmatically create a simple web server suitable for testing.

tl; dr - How to start programmatic launch of a simple web server inside a test?

+7
source share
3 answers

capybara uses a special Rack server for its specifications:

Any Rack application (including Rails applications) can be used using this system, although the Rails configuration can be a bit confusing.

+4
source

You can start your own simple server. A quick example of using thin and rspec (these gems, as well as the rack) should be set here:

 # spec/support/test_server.rb require 'rubygems' require 'rack' module MyApp module Test class Server def call(env) @root = File.expand_path(File.dirname(__FILE__)) path = Rack::Utils.unescape(env['PATH_INFO']) path += 'index.html' if path == '/' file = @root + "#{path}" params = Rack::Utils.parse_nested_query(env['QUERY_STRING']) if File.exists?(file) [ 200, {"Content-Type" => "text/html"}, File.read(file) ] else [ 404, {'Content-Type' => 'text/plain'}, 'file not found' ] end end end end end 

Then in spec_helper :

 # Include all files under spec/support Dir["./spec/support/**/*.rb"].each {|f| require f} # Start a local rack server to serve up test pages. @server_thread = Thread.new do Rack::Handler::Thin.run MyApp::Test::Server.new, :Port => 9292 end sleep(1) # wait a sec for the server to be booted 

This will serve any file that you store in the spec/support directory. Including yourself. For all other requests, it will return 404.

This is basically what capybara does, as mentioned in the previous answer, minus a lot of complexity.

+9
source

stub_server is a real testing server that can serve predefined answers and easily deploy ... comes with ssl support too.

+1
source

All Articles