Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to set test cookie for ActionCable? #887

Open
airblade opened this issue Mar 11, 2020 · 1 comment
Open

How to set test cookie for ActionCable? #887

airblade opened this issue Mar 11, 2020 · 1 comment

Comments

@airblade
Copy link

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
Copy link

Mattamorphic commented Sep 29, 2021

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  

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants