在ruby测试中启动Web服务器

时间:2012-04-15 22:13:16

标签: ruby rspec capybara tsung

我正在编写一个库,以一种可以被rails应用程序更好地使用的方式来包装tsung的功能。我想写一些归结为以下内容的集成测试:

  1. 启动简单的网络服务器
  2. 通过图书馆运行tsung-recorder
  3. 启动selenium,配置firefox配置文件以使用tsung代理,并从步骤1中启动的服务器获取页面
  4. 检查录制的库(它存在,它位于正确的位置等)
  5. 对于第1步,虽然我可以在外部启动一个vanilla rails应用程序(例如%x{rails s}),但我非常确定有一种更好的方法可以编程方式创建一个适合测试的简单Web服务器。

    tl; dr - 在测试中以编程方式启动简单Web服务器的方法是什么?

3 个答案:

答案 0 :(得分:9)

您可以滚动自己的简单服务器。这是一个使用thin和rspec的快速示例(必须安装那些gems,加上机架):

# 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

然后在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

这将为您存储在spec/support目录中的任何文件提供服务。包括自己。对于所有其他请求,它将返回404.

这基本上就像上一个答案中提到的水豚所做的那样,减去了很多复杂性。

答案 1 :(得分:4)

capybara使用ad-hoc Rack服务器进行规范:

可以使用此系统提供任何Rack应用程序(包括Rails应用程序),但Rails配置可能会有点棘手。

答案 2 :(得分:1)

stub_server是一个真正的测试服务器,可以提供预定义的回复,并且很容易启动...也支持ssl。