4

In my Rails (5.1) application I'm using devise for authentication and ActionCable.

My ActionCable connection looks like:

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      puts 'current_user:', current_user.inspect

      self.current_user = find_verified_user
      logger.add_tags 'ActionCable', current_user.id
    end

    def disconnect
      # ...
    end

    protected

    def find_verified_user
      verified_user = env['warden'].user
      return verified_user if verified_user

      reject_unauthorized_connection
    end
  end
end

Now I want to test it using action-cable-testing gem:

require 'rails_helper'

RSpec.describe ApplicationCable::Connection, type: :channel do
  let(:user) { create(:user) }

  before do
    stub_connection(current_user: user)
  end

  it 'successfully connects' do
    expect { connect '/cable' }.to_not raise_error
  end
end

But got error:

ApplicationCable::Connection
current_user:
nil
  successfully connects (FAILED - 1)

Failures:

  1) ApplicationCable::Connection successfully connects
     Failure/Error: expect { connect '/cable' }.to_not raise_error

       expected no Exception, got #<NoMethodError: undefined method `[]' for nil:NilClass> with backtrace:
         # ./app/channels/application_cable/connection.rb:19:in `find_verified_user'
         # ./app/channels/application_cable/connection.rb:8:in `connect'
         # /home/user/.rvm/gems/ruby-2.4.1/gems/action-cable-testing-0.3.1/lib/action_cable/connection/test_case.rb:176:in `connect'
         # ./spec/channels/user_channel_spec.rb:11:in `block (3 levels) in <top (required)>'
         # ./spec/channels/user_channel_spec.rb:11:in `block (2 levels) in <top (required)>'
     # ./spec/channels/user_channel_spec.rb:11:in `block (2 levels) in <top (required)>'

So I have two questions:

  1. Why current_user is nil?
  2. How do I authenticate user?
neversleep
  • 311
  • 1
  • 7
  • I found that `stub_connection` makes sense when dealing with channels, but it useless for connections. – neversleep May 27 '18 at 11:27
  • Solved. https://stackoverflow.com/questions/39741120/how-to-use-devise-token-auth-with-actioncable-for-authenticating-user – neversleep May 28 '18 at 05:01

1 Answers1

1

If you want to test Connection with current_user setup you should stub env['warden'] as shown here https://stackoverflow.com/a/53841098/7121891

If you want to test a Channel class, use action-cable-testing gem that already integrated into Rails 6