如何使用rspec对env ['warden'].user进行ApplicationCable :: Connection测试的存根 [英] How to stub env['warden'].user for ApplicationCable::Connection tests with rspec
本文介绍了如何使用rspec对env ['warden'].user进行ApplicationCable :: Connection测试的存根的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Rails 5.2我有以下ApplicationCable :: Connection红宝石文件:
Rails 5.2 I have the following ApplicationCable::Connection ruby file:
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测试:
I want to test this setup and and using the following RSpec test:
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
Failure/Error: if verified_user = env['warden'].user
NoMethodError:nil:NilClass的未定义方法"[]"
NoMethodError: undefined method `[]' for nil:NilClass
因此,我想存出env ['warden'].user代码并返回ID 325.我尝试了以下方法:
So I want to stub out the env['warden'].user code and return an id of 325. I tried the following:
allow(env['warden']).to receive(:user).and_return(325)
但这产生了以下错误:
未定义的局部变量或方法
env'
我如何测试该课程?
推荐答案
尝试一下:
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
这篇关于如何使用rspec对env ['warden'].user进行ApplicationCable :: Connection测试的存根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文