如何检查是否在迷你测试中调用了模拟的 class 方法?
How do I check if a mocked class method was calledin minitest?
我在 Rails 上使用 Minitest 和 Ruby 5. 如何断言调用了 void class 方法?我的 class
里有这个
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
但我不确定如何检查我的 "authenticate" 方法是否确实被调用了。
添加 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
及其概念
我在 Rails 上使用 Minitest 和 Ruby 5. 如何断言调用了 void class 方法?我的 class
里有这个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
但我不确定如何检查我的 "authenticate" 方法是否确实被调用了。
添加 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
及其概念