如何检查模拟类方法是否以最小的方式调用?

时间:2018-04-30 21:10:03

标签: unit-testing mocking ruby-on-rails-5 minitest ruby-on-rails-5.1

我正在使用Minitest和Ruby on Rails 5.如何断言调用了void类方法?我在课堂上有这个

module WebsocketClient
  class Proxy
    ...
    def self.authenticate(ws)
      auth_str = 'auth_str'
      ws.send auth_str
    end

然后在我的minitest文件中

  # Call the connect method
  WebsocketClient::Proxy.stub(:authenticate) do
    ws_client = WebsocketClient::Proxy.new(stratum_worker)
    ws_client.connect

    msg = WebSocket::Frame::Incoming::Client.new
    msg.data = error_str
    ws_client.websocket.emit :message, msg

    # Somehow verify that authenticate was called.
  end

但我不确定如何检查我的“身份验证”方法是否确实被调用。

1 个答案:

答案 0 :(得分:0)

添加Spy gem

https://github.com/ryanong/spy

然后你会像下面那样做

 # Call the connect method
  WebsocketClient::Proxy.stub(:authenticate) do
    ws_client = WebsocketClient::Proxy.new(stratum_worker)
    authenticate_spy = Spy.on(ws_client, :authenticate).and_call_through
    ws_client.connect

    msg = WebSocket::Frame::Incoming::Client.new
    msg.data = error_str
    ws_client.websocket.emit :message, msg

    # Somehow verify that authenticate was called.
    assert authenticate_spy.has_been_called?
  end

如果您不想执行实际方法并且只是监视它,那么您将使用

authenticate_spy = Spy.on(ws_client, :authenticate)

请参阅下面的更多示例,以熟悉Spy及其概念

https://github.com/ryanong/spy