Rails 5.2 我有以下ApplicationCable :: Connection红宝石文件:
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
message = "The user is not found. Connection rejected."
logger.add_tags 'ActionCable', message
self.transmit error: message
reject_unauthorized_connection
end
end
end
end
我要测试此设置并使用以下RSpec测试:
require 'rails_helper.rb'
RSpec.describe ApplicationCable::Connection, type: :channel do
it "successfully connects" do
connect "/cable", headers: { "X-USER-ID" => 325 }
expect(connection.user_id).to eq 325
end
end
哪个失败:
失败/错误:如果authenticated_user = env ['warden']。user
NoMethodError: nil:NilClass的未定义方法“ []”
因此,我想存出env ['warden']。user代码并返回ID 325。 我尝试了以下方法:
allow(env['warden']).to receive(:user).and_return(325)
但这产生了以下错误:
undefined local variable or method
环境
如何测试该课程?
答案 0 :(得分:1)
尝试一下:
require 'rails_helper.rb'
RSpec.describe ApplicationCable::Connection, type: :channel do
let(:user) { instance_double(User, id: 325) }
let(:env) { instance_double('env') }
context 'with a verified user' do
let(:warden) { instance_double('warden', user: user) }
before do
allow_any_instance_of(ApplicationCable::Connection).to receive(:env).and_return(env)
allow(env).to receive(:[]).with('warden').and_return(warden)
end
it "successfully connects" do
connect "/cable", headers: { "X-USER-ID" => 325 }
expect(connect.current_user.id).to eq 325
end
end
context 'without a verified user' do
let(:warden) { instance_double('warden', user: nil) }
before do
allow_any_instance_of(ApplicationCable::Connection).to receive(:env).and_return(env)
allow(env).to receive(:[]).with('warden').and_return(warden)
end
it "rejects connection" do
expect { connect "/cable" }.to have_rejected_connection
end
end
end
答案 1 :(得分:0)
对于您的问题https://stackoverflow.com/a/17050993/299774
,这是一个很好的解释问题是关于控制器测试的,但实际上是相似的。
我也不认为您应该在控制器中访问较低级别的env['warden']
。如果gem作者决定更改此设置,该怎么办-您必须修复您的应用。
可能使用这个配置初始化了看守对象,并且应该有一个可用的对象(运行规范时就没有必要-如上面的链接中所述)。