Search code examples
ruby-on-railsunit-testingminitestactioncable

How can I write unit tescase for action cable connection class in rails 6


following is my connection.rb

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

    def connect
      self.current_user = find_verified_user
    end

    private

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

How can I work on a unit test with the environment variable warden? Do I need to set it?


Solution

  • after too much of search I have got the solution for connection_test.rb

    # frozen_string_literal: true
    
    require "test_helper"
    
    module ApplicationCable
      class ConnectionTest < ActionCable::Connection::TestCase
        include ActionCable::TestHelper
    
        test "connects with devise" do
          user = users(:admin)
          connect_with_user(user)
          assert_equal connection.current_user, user
        end
    
        private
    
        def connect_with_user(user)
          connect env: { 'warden' => FakeEnv.new(user) }
        end
    
        class FakeEnv
          attr_reader :user
    
          def initialize(user)
            @user = user
          end
        end
      end
    end