Skip to content

Instantly share code, notes, and snippets.

@juanhiplogiq
Last active January 1, 2016 05:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanhiplogiq/8100263 to your computer and use it in GitHub Desktop.
Save juanhiplogiq/8100263 to your computer and use it in GitHub Desktop.
rspec testing ActionController::Live
#rspec testing ActionController::Live
#spec/controllers/post_controller_spec.rb
require 'spec_helper'
describe PostsController do
before :each do
controller.stub(:authenticate_user!)
@now = Time.now
Time.stub(:now).and_return(@now)
end
let(:valid_attributes) { { "body" => "MyString","headline" => "MyHeadline" } }
let(:valid_session) { {} }
describe "GET /posts/events" do
before :each do
@redis = mock(Redis)
@logger = mock(Logger)
@message = mock('Message')
@user = mock(User)
Redis.stub(:new).and_return(@redis)
@redis.stub(:psubscribe)
@redis.stub(:quit)
@redis.stub(:psubscribe).with('messages.*').and_yield(@message)
@message.stub(:pmessage).and_yield('pattern','event', 'data')
controller.stub(:current_user).and_return(@user)
@user.stub(:followees_latest_posts).and_return([])
end
it "should check if the latest post is there and write to the stream" do
@post = mock(Post, to_json: "post_json_data" )
@user.should_receive(:followees_latest_posts).and_return([@post])
get :events, {}
response.stream.instance_variable_get(:@buf)[0].should == "event: event\n"
response.stream.instance_variable_get(:@buf)[1].should == "data: post_json_data\n\n"
end
end
end
#app/controllers/posts_controller.rb
class PostsController < ApplicationController
include ActionController::Live
respond_to :html, :json
# GET /posts/events
#
def events
return unless current_user
event_stream('messages.*') do |data|
post = current_user.followees_latest_posts(where: { :created_at.gte => data }).first
post.to_json if post
end
render json: {}
end
def event_stream(channel, &block)
begin
response.headers["Content-Type"] = "text/event-stream"
redis = Redis.new
redis.psubscribe(channel) do |on|
on.pmessage do |pattern, event, data|
response.stream.write("event: #{event}\n")
response.stream.write("data: #{yield(data)}\n\n")
end
end
rescue IOError
logger.info("Stream closed")
ensure
redis.quit
response.stream.close
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment