如何测试包装在eventmachine中的sinatra app?

时间:2012-11-23 20:45:35

标签: ruby sinatra rack eventmachine

我有这个应用程序:

require 'sinatra/base'
require 'thin'

class WebService < Sinatra::Base
  get '/' do
    'hello'
  end
end

EM.run do
  EventMachine.add_periodic_timer(1) do
    puts 'hello'
  end

  Thin::Server.start(WebService)
end

我需要为其编写测试脚本。通常的方法不起作用,因为测试永远不会执行:

class WebServiceTest < Test::Unit::TestCase
  include Rack::Test::Methods

  def app
    WebService
  end

  def test
    get '/'
    assert last_response.ok?
  end
end

1 个答案:

答案 0 :(得分:0)

您需要将您的网络应用与您的事件计算机代码分开,以便您可以通过EM阻止线程来要求它:

webservice.rb:

require 'sinatra/base'

class WebService < Sinatra::Base
  get '/' do
    'hello'
  end
end

app.rb:

require 'thin'
require './webservice'

EM.run do
  EventMachine.add_periodic_timer(1) do
    puts 'hello'
  end

  Thin::Server.start(WebService)
end

然后在您的测试文件中,您需要webservice.rb才能对其进行测试:

require './webservice'

class WebServiceTest < Test::Unit::TestCase
  include Rack::Test::Methods

  def app
    WebService
  end

  def test
    get '/'
    assert last_response.ok?
  end
end