首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Ruby EventMachine测试

Ruby EventMachine测试
EN

Stack Overflow用户
提问于 2013-05-21 22:39:29
回答 1查看 2K关注 0票数 7

我的第一个关于Ruby的问题。我正在尝试测试反应器循环中的EventMachine交互--我想这可以归类为“功能”测试。

假设我有两个类-一个服务器和一个客户端。我想测试两个方面--我需要确定他们之间的交互。

服务器:

代码语言:javascript
复制
require 'singleton'

class EchoServer < EM::Connection
  include EM::Protocols::LineProtocol

  def post_init
    puts "-- someone connected to the echo server!"
  end

  def receive_data data
    send_data ">>>you sent: #{data}"
    close_connection if data =~ /quit/i
  end

  def unbind
    puts "-- someone disconnected from the echo server!"
  end
end

客户端:

代码语言:javascript
复制
class EchoClient < EM::Connection
  include EM::Protocols::LineProtocol

  def post_init
    send_data "Hello"
  end

  def receive_data(data)
    @message = data
    p data
  end

  def unbind
    puts "-- someone disconnected from the echo server!"
  end
end

因此,我尝试了不同的方法,但一无所获。

最基本的问题是--我可以用某种方式用RSpec测试我的代码,使用should_recive吗?

EventMachine参数应该是一个类或模块,所以我不能在里面发送实例化/模拟的代码。对吗?

像这样的东西?

代码语言:javascript
复制
describe 'simple rspec test' do
  it 'should pass the test' do
    EventMachine.run {
      EventMachine::start_server "127.0.0.1", 8081, EchoServer
      puts 'running echo server on 8081'

      EchoServer.should_receive(:receive_data)

      EventMachine.connect '127.0.0.1', 8081, EchoClient

      EventMachine.add_timer 1 do
        puts 'Second passed. Stop loop.'
        EventMachine.stop_event_loop
      end
    }
  end
end

如果不是这样,您将如何使用EM::SpecHelper来完成此任务?我有这段代码在使用它,但是我不知道我做错了什么。

代码语言:javascript
复制
describe 'when server is run and client sends data' do
  include EM::SpecHelper

  default_timeout 2

  def start_server
    EM.start_server('0.0.0.0', 12345) { |ws|
      yield ws if block_given?
    }
  end

  def start_client
    client = EM.connect('0.0.0.0', 12345, FakeWebSocketClient)
    yield client if block_given?
    return client
  end

  describe "examples from the spec" do
    it "should accept a single-frame text message" do
      em {
        start_server

        start_client { |client|
          client.onopen {
            client.send_data("\x04\x05Hello")
          }
        }
      }
    end
  end
end

我尝试了很多这些测试的变体,但我就是搞不明白。我肯定我错过了什么..。

谢谢你的帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-05-24 12:30:35

我能想到的最简单的解决方案是改变这一点:

代码语言:javascript
复制
EchoServer.should_receive(:receive_data)

要这样做:

代码语言:javascript
复制
EchoServer.any_instance.should_receive(:receive_data)

因为EM期望一个类启动服务器,所以上面的any_instance技巧将期望该类的任何实例接收该方法。

EMSpecHelper示例(虽然是官方的/标准的)相当复杂,为了简单起见,我宁愿使用第一个rspec并使用any_instance

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16672763

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档