【问题标题】:Ruby EventMachine testingRuby EventMachine 测试
【发布时间】:2013-05-21 14:39:28
【问题描述】:

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

假设我有两个类——一个服务器和一个客户端。而且我想测试双方 - 我需要确定他们的互动。

服务器:

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

客户:

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

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

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

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

这样的?

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 来实现?我有这段代码正在使用它,但无法弄清楚我做错了什么。

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

尝试了这些测试的很多变体,但我就是想不通。我确定我在这里遗漏了一些东西......

感谢您的帮助。

【问题讨论】:

    标签: ruby rspec eventmachine


    【解决方案1】:

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

    EchoServer.should_receive(:receive_data)
    

    到这里:

    EchoServer.any_instance.should_receive(:receive_data)
    

    由于 EM 期望类启动服务器,因此上述 any_instance 技巧将期望该类的任何实例接收该方法。

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

    【讨论】:

    • 它有效。要记住的一件事是 should_recive 存根该方法,因此它的行为就像该方法中没有任何内容一样。谢谢。
    • 是的,RSpec 从 v2.12 开始也支持calling the original method again
    • 如果可以的话+10!这就是我多年来一直在寻找的东西!
    猜你喜欢
    • 2011-04-29
    • 1970-01-01
    • 2011-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 2012-11-16
    相关资源
    最近更新 更多