如何用rspec成功模拟赛璐珞

时间:2018-03-28 14:57:42

标签: rspec celluloid

嗯,我很累。在某种意义上用尽了选项。

我们有管理演员的主管。

supervisor = Celluloid::SupervisionGroup.run!

airbrake = supervisor.pool(Flango::AirbrakeActor, as: :airbrake_actor, size: 1)

我需要做的就是模仿airbrake actor,其中定义了notify_exception ..方法。

即以下电话

airbrake.async.notify_exception('exception') 

相关的rspec代码......

expect(airbrake.async).to receive(:notify_exception).with('exception')

我尝试了this ..不起作用

尝试了以下方法(不确定我在做什么)

airbrake = OpenStruct.new(:async, Flango::AirbrakeActor.new)

这项工作,但测试在结束时挂起,直到被杀。

任何帮助?

1 个答案:

答案 0 :(得分:1)

我能够在2次更改后使其工作。

一个问题是你正在关闭赛璐珞然后使用死变量。所以我在init

中重构了启动代码
require 'bundler'
Bundler.setup(:default)
require 'ffi-rzmq'
require 'celluloid/zmq'
require 'celluloid/current'
require 'securerandom'
Celluloid::ZMQ.init
class SockOne
  include Celluloid::ZMQ
  attr_reader :sock
  def initialize
    @sock = PullSocket.new
    @sock.connect('tcp://127.0.0.1:20483')
  end

  def read
    loop do
      middleware.async.start(sock.read_multipart)
    end
  end
end

class SockTwo
  include Celluloid::ZMQ
  attr_reader :sock
  def initialize
    @sock = PushSocket.new
    @sock.connect('tcp://127.0.0.1:20484')
  end

  def send_response(other_id, id, response)
    start_time = Time.now
    sock.send(response)
  end
end

class Middleware
  include Celluloid
  def start(data)
    puts "i am starting middleware with " + data
    Handler.new.start(data)
  end
end

class Handler
  def start(data)
    begin
      execute(data)
    rescue => exception
      airbrake.async.notify('some exception')
    ensure
      sock_two.async.send_response(['i got a reply'])
    end
  end

  def execute(data)
    data
  end
end

class Airbrake
  include Celluloid
  def notify(data)
    puts "this is notify to airbrake - " + data
  end
end

def init
  supervisor = Celluloid::SupervisionGroup.run!
  $middleware = supervisor.pool(Middleware, as: :middleware, size: 10)
  $sock_two = supervisor.pool(SockTwo, as: :sock_two, size: 10)
  $airbrake = supervisor.pool(Airbrake, as: :airbrake, size: 1)
end

def airbrake
  $airbrake
end

def sock_two
  $sock_two
end

def middleware
  $middleware
end

if $0 == __FILE__
  puts "Starting.."
  sock_one = SockOne.new
  sock_one.read
end

然后重构main_spec.rb,如下所示

require 'rspec'

require_relative 'main'

describe 'Handler' do
  describe '#start' do
    before(:each) do
      Celluloid.shutdown
      #init()
      Celluloid.boot
      init()
    end

    it 'should invoke async call to celluloid' do
      handler = Handler.new
      expect(handler).to receive(:execute).with(['1', '2', '3']).and_raise('boom')

      # This does not work
       airbrake.wrapped_object.instance_eval do
         def notify(data)
            puts "new data was called - " + data
         end
       end

      expect(airbrake.wrapped_object).to receive(:notify).with('some exception')

      handler.start(['1', '2', '3'])
    end

    after(:each) do
      Celluloid.shutdown
    end
  end
end

现在可行了

Working test