Search code examples
rspectwitter-streaming-apivcrtwitter-gem

How can I mock twitter streaming client calls within rspec?


Using rspec and the twitter gem https://github.com/sferik/twitter

I am trying to find a solution to mock a twitter stream ideally with a mechanism like VCR. Obviously VCR does not work on tcp socket connections only http requests.

If this is too much to ask, any hints about where to stub what would be helpful.


Solution

  • so I found that best place to stub is here https://github.com/sferik/twitter/blob/master/lib/twitter/streaming/connection.rb#L21

    first record your stream by first temporarily monkeypatching SSLSocket#readpartial in your spec file running one spec

    module OpenSSL::SSL
      class SSLSocket
        F = File.open("fixtures/twitter/stream0.txt","w")
        def readpartial(*args)
          res = super(*args)
          F.write res
          F.flush
          res
        end
      end
    end
    

    when your fixture is done. you can stub like:

    OpenSSL::SSL::SSLSocket.any_instance.should_receive(:readpartial).with(1024).and_return(File.read("fixtures/twitter/stream0.txt")