我有这段代码来验证频道订阅者:
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = find_verified_user
end
protected
def find_verified_user
if current_user = User.find_by(id: cookies.signed[:user_id])
current_user
else
reject_unauthorized_connection
end
end
end
end
一切正常。问题出在功能测试中。 当我运行此测试时:
require 'rails_helper'
feature 'Chat room' do
scenario "send one message" do
user = create(:user)
login_as(user, :scope => :user)
expect {
fill_in 'message', with: 'hello friend'
click_button 'Send'
byebug
}.to change(Message, :count).by(1)
expect(current_path).to eq root_path
expect(page).to have_content 'hello friend'
end
end
测试日志表示“未经授权的连接尝试被拒绝”。由于cookie为空,因此无法进行身份验证。
那么如何在水豚测试中设置cookie?
我尝试在测试中执行此操作cookies.signed[:user_id] = user.id
,但它不起作用。
如何在测试中设置像cookies.signed[:user_id] = user.id
这样的cookie?
答案 0 :(得分:0)
假设您正在呼叫的login_as
来自Warden测试帮助程序,它的作用是设置为使下一个请求在响应中设置会话cookie。因此,您可能需要在致电login_as
后访问某个页面。此外,自点击发送&#39;是异步的,你需要在检查Message.count发生变化之前等待某些事情发生变化,如果你想进行非片状测试,你真的不应该使用带有current_path的.eq。所以所有这些都结合了
#don't visit the page where you can fill in the message before calling login_as
scenario "send one message" do
user = create(:user)
login_as(user, :scope => :user)
visit 'the path to the page where you can fill in a message'
expect {
fill_in 'message', with: 'hello friend'
click_button 'Send'
expect(page).to have_css('#messages', text:'hello friend') # adjust selector depending on where the message is supposed to appear
expect(page).to have_current_path(root_path)
}.to change(Message, :count).by(1)
end
应该适合你