【问题标题】:Creating a dummy server for unit testing in Ruby在 Ruby 中为单元测试创​​建一个虚拟服务器
【发布时间】:2011-09-09 19:16:11
【问题描述】:

我维护了一些使用 net/http 处理远程文件的 Ruby gem。

我当前的单元测试设置包括在setup 方法中启动一个WEBrick 服务器,然后在teardown 中终止它。

def setup
  return if @server_thread
  @server_thread = Thread.new do
    s = WEBrick::HTTPServer.new(:Port => 12000, :DocumentRoot => www_root, :Logger => Log.new(nil, BasicLog::ERROR), :AccessLog => [])
    port = s.config[:Port]
    begin
      s.start
    ensure
      s.shutdown
    end
  end
end

在 Ruby 1.9.2 和 1.9.3 中,我遇到了一堆连接错误 - Errno::ECONNREFUSED: Connection refused - connect(2)。更令人沮丧的是它们是短暂的——有时它们会发生,有时不会。我能想到的只是 WEBrick 要么不堪重负,要么一开始就没有正确设置。

我需要能够通过 HTTP 加载多个静态文件(在我的 fixtures 目录中)来测试这些 gem。创建用于Test::Unit 测试的虚拟 HTTP 服务器的最佳做法是什么?

【问题讨论】:

    标签: ruby unit-testing http testing


    【解决方案1】:

    我会模拟 net/http 类以返回静态文件内容。使用依赖注入,以便被测类在单元测试执行期间使用模拟,在生产中使用net/http

    您还可以使用 webmockfakeweb gems。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-05
      • 1970-01-01
      • 2021-05-22
      • 1970-01-01
      • 2011-08-17
      • 1970-01-01
      • 2015-11-29
      • 1970-01-01
      相关资源
      最近更新 更多