user3809888
user3809888

Reputation: 407

How to mock a streaming API with RSpec?

I'm playing around with the tweetstream gem, which simplifies interaction with the Twitter streaming API. I'm streaming all tweets just like the code example shown on the gem's page:

TweetStream::Client.new.sample do |status|
  puts "#{status.text}"
end

I've put this in a #capture method with some simple logic to run the stream for only a few seconds and capture all the tweets (the status.text strings) in an array.

I want to write unit tests for #capture. How would I stub out the stream of tweets? I'm guessing I'll have store tweets in either a file or a StringIO object, but I don't know how to write the mock to handle whatever TCP interaction is going on with the streaming API. I'm not sure if I should use VCR here, either.

Upvotes: 0

Views: 779

Answers (1)

Rishav Rastogi
Rishav Rastogi

Reputation: 15482

Read the article for a very simple way to test External services using the VCR gem https://robots.thoughtbot.com/how-to-stub-external-services-in-tests

Lot of people might suggest using this method below, its incomplete and brittle so best to avoid it.

 client = Twitter::Client.new
 client.stub(:sample).and_yield(:message)

Upvotes: 0

Related Questions