我的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
文件与红宝石指南中的文件相同:
// 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
我得到的错误是: 失败/错误:如果current_user&.account_id
NameError:
undefined local variable or method `current_user' for #<MessageNotificationsChannel:0x000000000721d890>
错误的位置在我的message_notifications_channel.rb
文件中。我在byebug
的{{1}}方法中的self.current_user = find_verified_user
之前放置了connect
,测试根本无法解决这个问题。毫不奇怪,我稍后会收到该错误。
当我在开发环境中运行时,byebug将受到攻击,并且一切将正常运行。
这是我的connection.rb
:
cable.yml
我看过https://github.com/palkan/action-cable-testing/issues/26#issuecomment-392481619 该人的代码并未真正使用Devise。我的应用程序的所有部分都必须使用devise进行用户身份验证,这一点至关重要。 谢谢!
答案 0 :(得分:1)
尝试将“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