【问题标题】:Use cookies.signed[:user_id] in capybara tests在水豚测试中使用 cookies.signed[:user_id]
【发布时间】:2016-06-30 18:23:57
【问题描述】:

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

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?

【问题讨论】:

  • 您对login_as 的定义是什么?您实际访问页面的时间/地点是什么?

标签: ruby-on-rails cookies rspec capybara actioncable


【解决方案1】:

假设您调用的 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

应该适合你

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多