首页 > 解决方案 > 使用 Devise 进行动作电缆测试

问题描述

我的 Ruby on Rails 应用程序可以正常工作。事情正在按我的意愿广播和接收。action-cable-testing但是,我想使用gem向通道添加单元测试。我的用户注册是使用Devise. 这是我的connection.rb文件:

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

    def connect
      self.current_user = find_verified_user
    end

    private
    def find_verified_user
      if verified_user = env['warden'].user
        verified_user
      else
        reject_unauthorized_connection
      end
    end
  end
end

我有一个message_notifications_channel.rb这样的:

class MessageNotificationsChannel < ApplicationCable::Channel
  def subscribed
    # stream_from "some_channel"
    if current_user&.account_id
      stream_from "message_notifications_channel_#{current_user.account_id}"
    end
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end
end

此频道允许用户在登录时从message_notifications_channel_accountID其中 accountID 是用户所属帐户的 ID 进行流式传输。

我的cable.js文件与 ruby​​ 指南中显示的相同:

// Action Cable provides the framework to deal with WebSockets in Rails.
// You can generate new channels where WebSocket features live using the `rails generate channel` command.
//
//= require action_cable
//= require_self
//= require_tree ./channels

(function() {
  this.App || (this.App = {});

  App.cable = ActionCable.createConsumer();

}).call(this);

我在使用以下 rspec 测试时遇到问题:

require 'rails_helper'

RSpec.describe MessageNotificationsChannel, type: :channel do
  let(:authorized_senders) {['11111']}
  let(:common_user_phone){'17777777777'}
  let(:account) {FactoryGirl.create(:account, authorized_senders: authorized_senders)}
  let(:user){FactoryGirl.create(:user, account: account, admin: true)}
  context 'when user is authenticated' do
    describe '#connect' do
      it 'accepts connection' do
        sign_in user
        subscribe(account_id: user.account_id)
      end
    end
  end
end

我得到的错误是:Failure/Error: if current_user&.account_id

 NameError:
   undefined local variable or method `current_user' for #<MessageNotificationsChannel:0x000000000721d890>

错误的位置在我的message_notifications_channel.rb文件中。我在方法中放了一个byebugbefore ,测试根本不会碰到那个 byebug。毫不奇怪,我稍后会收到该错误。self.current_user = find_verified_userconnectconnection.rb

当我在开发环境中运行时,byebug 会被击中并且事情会正常运行。

这是我的cable.yml

redis: &redis
  adapter: redis
  url: redis://localhost:6379/1

production: *redis
development: *redis
test:
 *redis

我查看了https://github.com/palkan/action-cable-testing/issues/26#issuecomment-392481619 该人的代码并没有真正使用设计。我的应用程序的所有部分都使用设计进行用户身份验证,这一点至关重要。谢谢!

标签: ruby-on-railsrspecdevisechannelactioncable

解决方案


尝试将“ stub_connection current_user: users(:some_user_from_fixtures) ”添加到您的测试中。因此,对于您的代码,它将是:

   it 'accepts connection' do
        sign_in user
        stub_connection current_user: user
        subscribe(account_id: user.account_id)
   end

这应该有效。更多信息请访问 rails 官方文档:Testing Action Cable


推荐阅读