繁体   English   中英

如何使用 rspec 测试 ActionCable 和 Devise?

[英]How to test ActionCable along with Devise using rspec?

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

我的 ActionCable 连接看起来像:

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 测试它:

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_usernil
  2. 我如何验证用户?

如果要测试与current_user设置的连接,您应该存根env['warden']如下所示https://stackoverflow.com/a/53841098/7121891

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM