Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Test Pusher with RSpec

I am using Pusher for facebook style notifications. I have setup a simple RSpec test to test that Pusher is triggered.

scenario "new comment should notify post creator" do
  sign_in_as(user)
  visit user_path(poster)
  fill_in "comment_content", :with => "Great Post!"
  click_button "Submit"

  client = double
  Pusher.stub(:[]).with("User-1").and_return(client)
  client.should_receive(:trigger)
end

This test passes. However if I make another test using identical code (testing the same thing twice), the second test does not pass. It does not matter if I put the second test in the same file or a different one. I can essentially only test Pusher once.

The error that I get for the second test is...

Failure/Error: client.should_receive(:trigger)
  (Double).trigger(any args)
    expected: 1 time with any arguments
    received: 0 times with any arguments
like image 326
tob88 Avatar asked Nov 22 '13 12:11

tob88


1 Answers

This may be an old question but I wanted to add my answer. When testing Pusher with RSpec previously in a Rails app, we wrote feature specs as follows:

it "user can publish the question" do
  expect_any_instance_of(Pusher::Client).to receive(:trigger)
  visit event_path(event)
  click_on 'Push Question to Audience'
  expect(current_path).to eq  question_path(@question)
  expect(page).to have_content 'Question has been pushed to the audience'
end

We also used Pusher Fake which is a fake Pusher server for development and testing available at https://github.com/tristandunn/pusher-fake.

"When run, an entire fake service is started on two random open ports. Connections can then be made to the service without needing a Pusher account. The host and port for the socket and web servers can be found by checking the configuration." This then allows you to do:

require "rails_helper"

feature "Server triggering a message" do
  before do
    connect
    connect_as "Bob"
  end

  scenario "triggers a message on the chat channel", js: true do
    trigger "chat", "message", body: "Hello, world!"

    expect(page).to have_content("Hello, world!")

    using_session("Bob") do
      expect(page).to have_content("Hello, world!")
    end
  end

  protected

  def trigger(channel, event, data)
    Pusher.trigger(channel, event, data)
  end
end

A an example repo to show this approach can be found at https://github.com/tristandunn/pusher-fake-example

like image 86
Ben Hawker Avatar answered Oct 16 '22 01:10

Ben Hawker