如何使用rspec测试ActionCable和Devise? [英] How to test ActionCable along with Devise using rspec?

查看:66
本文介绍了如何使用rspec测试ActionCable和Devise?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Rails(5.1)应用程序中,我正在使用devise进行身份验证和ActionCable.

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

我的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

现在我想使用 action-cable-testing gem测试它:

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

但是出现错误:

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)>'

所以我有两个问题:

  1. 为什么 current_user nil ?
  2. 如何验证用户身份?

推荐答案

如果要使用 current_user 设置测试连接,则应将 env ['warden'] 存根为在此处显示 https://stackoverflow.com/a/53841098/7121891

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

如果您要测试Channel类,请使用 action-cable-testing 已经集成到Rails 6中的宝石

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

这篇关于如何使用rspec测试ActionCable和Devise?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆