thoughtbot / clearance

Rails authentication with email & password.
https://thoughtbot.com
MIT License
3.71k stars 457 forks source link

How to set test cookie for ActionCable? #887

Open airblade opened 4 years ago

airblade commented 4 years ago

Hello!

I am trying to write a test for an ActionCable connection. My connection class looks like this:

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

    def connect
      self.current_user = find_user
      reject_unauthorized_connection unless self.current_user
    end

    private

    #
    # Code below copied from Clearance::Session
    #

    def find_user
      if remember_token.present?
        @current_user ||= user_from_remember_token(remember_token)
      end

      @current_user
    end

    def cookies
      @cookies ||= ActionDispatch::Request.new(@env).cookie_jar
    end

    def remember_token
      cookies[Clearance.configuration.cookie_name.freeze]
    end

    def user_from_remember_token(token)
      Clearance.configuration.user_model.where(remember_token: token).first
    end
  end
end

I am trying to write a test along the lines recommended in the Rails docs:

test "connects with cookies" do
  user = User.create remember_token: 42

  cookies.signed[:remember_token] = "42"

  connect

  assert_equal user.id, connection.current_user.id
end

However the remember token cookie doesn't seem to get set. I also tried cookies[:remember_token] = "42".

I'd greatly appreciate any advice for how to get this working. Thanks!

Mattamorphic commented 3 years ago

Probably long since resolved, but if anyone else faces issues I think you need to query the env off of the connection object in action cable:

def cookies
  @cookies ||= ActionDispatch::Request.new(connection.env).cookie_jar
end