Ruby EventMachine Rspec连接和发送数据测试不工作
我正在尝试更新em irc库,使其能够与当前版本的Ruby一起工作,并使用一些新特性对其进行更新。我正试图使规范适用于我的更改,但它没有像我预期的那样工作 不管我引入了什么样的更改,其中一个不起作用的测试是send_数据上下文Ruby EventMachine Rspec连接和发送数据测试不工作,ruby,rspec,eventmachine,Ruby,Rspec,Eventmachine,我正在尝试更新em irc库,使其能够与当前版本的Ruby一起工作,并使用一些新特性对其进行更新。我正试图使规范适用于我的更改,但它没有像我预期的那样工作 不管我引入了什么样的更改,其中一个不起作用的测试是send_数据上下文 subject do EventMachine::IRC::Client.new end ... context 'send_data' do let(:connection) { mock('Connection') } be
subject do
EventMachine::IRC::Client.new
end
...
context 'send_data' do
let(:connection) { mock('Connection') }
before do
subject.stub(:conn => connection)
subject.stub(:connected => true)
end
it 'should return false if not connected' do
subject.stub(:connected => false)
subject.send_data("NICK jch").should == false
end
it 'should send message to irc server' do
connection.should_receive(:send_data).with("NICK jch\r\n")
subject.send_data("NICK jch")
end
end
在我的代码中引用此函数的:
def send_data(message)
return false unless @connected
message = message + "\r\n"
@conn.send_data(message)
trigger 'send', message
end
第一次测试工作;当主题未连接时,发送_数据返回false。但是,第二个测试失败,因为模拟“连接”从未收到发送数据调用。这就是我收到的失败:
1) EventMachine::IRC::Client send_data should send message to irc server
Failure/Error: connection.should_receive(:send_data).with("NICK jch\r\n")
(Mock "Connection").send_data("NICK jch\r\n")
expected: 1 time with arguments: ("NICK jch\r\n")
received: 0 times with arguments: ("NICK jch\r\n")
# ./spec/lib/em-irc/client_spec.rb:80:in `block (3 levels) in <top (required)>'
我尝试了一些改变,但似乎没有一个奏效。我不明白为什么即使我在模拟连接上调用send_数据,连接也不接收send_数据调用。它在库的前一个版本中工作,唯一的区别是我使用let:connection{…},而不是@connection=mock'connection' 在rspec中,您需要在事件循环中运行测试。我通过这个猴子补丁实现了这一点:
RSpec::Core::Example.class_eval do
alias ignorant_run run
def run(example_group_instance, reporter)
result = false
Fiber.new do
EM.run do
df = EM::DefaultDeferrable.new
df.callback do |test_result|
result = test_result
# stop if we are still running.
# We won't be running if something inside the test
# stops the run loop.
EM.stop if EM.reactor_running?
end
test_result = ignorant_run example_group_instance, reporter
df.set_deferred_status :succeeded, test_result
end
end.resume
result
end
end
您需要显示更多的代码,包括@connected和@conn是如何初始化的。即使我在存根它们,这会影响它们吗?我对rspec不是很精通,所以我不太清楚。@conn和@connected会影响被测代码的行为,这会影响您得到的结果。你不能存根实例变量,它们是什么,所以你需要展示这些实例变量是如何设置的。哦,真的吗?我认为我更改的代码影响了这一点,我试图存根实例变量。我猜你必须在测试中引用变量集,而不是存根?