Testing Ruby EventMachine

My first question is about Ruby. I am trying to test the interaction of EventMachine within the Reactor cycle - I think it could be attributed to β€œfunctional” testing.

Let's say I have two classes - server and client. And I want to check both sides - I have to be sure of their interaction.

Server:

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 

Client:

 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 

So, I tried different approaches and came up with nothing.

The main question is: can I somehow test my code with RSpec using should_recive?

The EventMachine parameter must be a class or module, so I cannot send instance / wrap code internally. Correctly?

Something like that?

 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 

And if not, how would you do it with EM :: SpecHelper? I use this code and cannot understand what I am doing wrong.

 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 

Tried a lot of variations of these tests, and I just can't figure it out. I'm sure something is missing here ...

Thank you for your help.

+7
source share
1 answer

The simplest solution I can think of is to change this:

 EchoServer.should_receive(:receive_data) 

For this:

 EchoServer.any_instance.should_receive(:receive_data) 

Since EM expects the class to start the server, the above any_instance trick expects any instance of this class to receive this method.

The EMSpecHelper example (being official / standard) is pretty confusing, I'd rather stick with the first rspec and use any_instance for simplicity.

+4
source

All Articles