【发布时间】:2012-07-07 11:03:27
【问题描述】:
我正在尝试整个BDD 方法,并想测试我正在编写的香草Ruby 应用程序的基于AMQP 的方面。在选择 Minitest 作为测试框架以平衡其功能和表现力而不是其他恰当命名的蔬菜框架后,我开始编写此规范:
# File ./test/specs/services/my_service_spec.rb
# Requirements for test running and configuration
require "minitest/autorun"
require "./test/specs/spec_helper"
# External requires
# Minitest Specs for EventMachine
require "em/minitest/spec"
# Internal requirements
require "./services/distribution/my_service"
# Spec start
describe "MyService", "A Gateway to an AMQP Server" do
# Connectivity
it "cannot connect to an unreachable AMQP Server" do
# This line breaks execution, commented out
# include EM::MiniTest::Spec
# ...
# (abridged) Alter the configuration by specifying
# an invalid host such as "l0c@alho$t" or such
# ...
# Try to connect and expect to fail with an Exception
MyApp::MyService.connect.must_raise EventMachine::ConnectionError
end
end
我已经注释掉了包含 the em-minitest-spec gem 的功能,它应该强制规范在 EventMachine 反应器内运行,如果我包含它,我会遇到一个关于(我想)内联类等的更粗略的异常:NoMethodError: undefined method 'include' for #<#<Class:0x3a1d480>:0x3b29e00>.
我正在测试的代码,即该服务中的connect 方法基于on this article,如下所示:
# Main namespace
module MyApp
# Gateway to an AMQP Server
class MyService
# External requires
require "eventmachine"
require "amqp"
# Main entry method, connects to the AMQP Server
def self.connect
# Add debugging, spawn a thread
Thread.abort_on_exception = true
begin
@em_thread = Thread.new {
begin
EM.run do
@connection = AMQP.connect(@settings["amqp-server"])
AMQP.channel = AMQP::Channel.new(@connection)
end
rescue
raise
end
}
# Fire up the thread
@em_thread.join
rescue Exception
raise
end
end # method connect
end
end # class MyService
整个“异常处理”只是试图将异常冒泡到我可以捕获/处理它的地方,不管有没有begin,这都无济于事和raise bits 在运行规范时我仍然得到相同的结果:
EventMachine::ConnectionError: unable to resolve server address,这实际上是我所期望的,但Minitest 与整个反应堆概念并没有很好地配合,并且在这个Exception 的地面测试中失败了。
那么问题仍然存在:如何使用Minitest 的规范机制测试与EventMachine 相关的代码? Another question 也一直在徘徊关于 Cucumber 的问题,也没有得到答复。
或者我应该专注于我的主要功能(例如消息传递和查看消息是否被发送/接收)而忘记边缘情况?任何见解都会真正有帮助!
当然,这都可以归结为我上面写的代码,也许这不是编写/测试这些方面的方式。可能!
关于我的环境的注释:ruby 1.9.3p194 (2012-04-20) [i386-mingw32](是的,Win32 :>)、minitest 3.2.0、eventmachine (1.0.0.rc.4 x86-mingw32)、amqp (0.9.7)
提前致谢!
【问题讨论】:
-
好吧,最终证明有效的方法是在规范中使用
begin--rescue块调用connect,must_raise断言进入该块。但是测试真的很慢(重试、超时等),我可能会完全放弃它,主要是考虑到下面 Ben 的回答。
标签: ruby testing amqp eventmachine minitest