在ruby测试中启动Web服务器

Ben*_*aum 8 ruby rspec capybara tsung

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

  1. 启动一个简单的Web服务器
  2. 通过图书馆运行tsung-recorder
  3. 使用配置为使用tsung代理的firefox配置文件启动selenium,并从步骤1中启动的服务器获取此页面
  4. 检查记录的库(它存在,它在正确的位置,等等)

对于第1步,虽然我可以在外部启动一个vanilla rails应用程序(例如%x{rails s}),但我很确定有一种更好的方法可以以编程方式创建一个适合测试的简单Web服务器.

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

Thi*_*ilo 10

您可以滚动自己的简单服务器.这是一个使用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
Run Code Online (Sandbox Code Playgroud)

然后在你的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
Run Code Online (Sandbox Code Playgroud)

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

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


Nik*_* B. 5

capybara使用临时的Rack服务器为其规格:

可以使用此系统为任何Rack应用程序(包括Rails应用程序)提供服务,尽管Rails配置可能会有些棘手。