1

我有这个代码来验证频道订阅者:

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 为空,因此无法进行身份验证。

那么如何在 capybara 测试中设置 cookie?

我在测试中尝试过这样做cookies.signed[:user_id] = user.id,但它不起作用。

如何cookies.signed[:user_id] = user.id在测试中设置这样的 cookie?

4

1 回答 1

0

假设login_as您调用的是 Warden 测试助手,它所做的设置是为了让下一个请求在响应中设置会话 cookie。因此,您可能需要在调用login_as. 此外,由于单击“发送”是异步的,因此您需要等待某些内容发生更改,然后再检查 Message.count 是否已更改,并且如果您想要非易碎测试,您真的不应该将 with .eq 与 current_path 一起使用。所以所有的东西都结合起来了

#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

应该为你工作

于 2016-03-15T18:20:11.367 回答