1

我有这个应用程序:

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
4

1 回答 1

0

您需要将您的网络应用程序与您的事件机器代码分开,这样您就可以在没有 EM 阻塞线程的情况下要求它:

网络服务.rb:

require 'sinatra/base'

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

应用程序.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
于 2012-11-24T05:53:45.800 回答