如何使用rspec测试ActionCable和Devise?

时间:2018-05-27 05:56:25

标签: ruby-on-rails rspec devise

在我的Rails(5.1)应用程序中,我正在使用设计进行身份验证和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. 如何验证用户身份?

1 个答案:

答案 0 :(得分:0)

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

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