如何在我的Rails单元测试中注入模拟?

时间:2018-04-05 20:04:46

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

我试图弄清楚如何在我的测试中注入模拟,使用Rails 5.1和minitest。我正在测试以下类的这种方法......

module WebsocketClient
  class Proxy
    ...
    def connect
      @websocket = WebSocket::Client::Simple.connect @websocket_url

我想要一行

WebSocket::Client::Simple.connect @websocket_url

返回模拟而不是实际尝试连接,所以我尝试在单元测试中执行此操作

  test "connect with open" do
    my_worker = my_workers(:one)
    assert my_worker.websocket_url.present?, "A pre-condition of this test is that the stratum worker have a websocket URL defined."
    proxy = WebsocketClient::Proxy.new( my_worker )

    # Stub call to connect
    mock_ws = MiniTest::Mock.new
    WebSocket::Client::Simple.stub(:connect, my_worker.websocket_url) do
      mock_ws
    end

    # Call the connect method
    ws_client = WebsocketClient::Proxy.new(my_worker)
    ws_client.connect

然而,在运行我的测试时,模拟没有被执行。相反," WebSocket :: Client :: Simple.connect @ websocket_url"被称为正常。如何在我的测试中注入我的模拟?

0 个答案:

没有答案