Rails 5.2我有以下ApplicationCable::Connection ruby文件:
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这会失败,出现以下错误:
失败/错误:如果verified_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环境
我如何测试这个类?
发布于 2018-12-19 05:09:28
试试这个:
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发布于 2018-12-19 18:46:06
这里有一个很好的解释来解释你的问题https://stackoverflow.com/a/17050993/299774
这个问题是关于控制器测试的,但它实际上是相似的。
我也不认为你应该在你的控制器中访问低级env['warden']。如果gem的作者决定改变这一点怎么办-你必须修复你的应用程序。可能warden对象是使用此配置初始化的,并且应该有一个对象可用(只是在运行您的规范时不是必需的-如上面的链接所述)。
https://stackoverflow.com/questions/53800410
复制相似问题