ruby-on-rails - 如何使用 rspec 测试 ActionCable 和 Devise?

标签 ruby-on-rails rspec devise

在我的 Rails (5.1) 应用程序中,我使用 devise 进行身份验证和 ActionCable。

我的 ActionCable 连接看起来像:

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      puts 'current_user:', current_user.inspect

      self.current_user = find_verified_user
      logger.add_tags 'ActionCable', current_user.id
    end

    def disconnect
      # ...
    end

    protected

    def find_verified_user
      verified_user = env['warden'].user
      return verified_user if verified_user

      reject_unauthorized_connection
    end
  end
end

现在我想使用 action-cable-testing gem 测试它:

require 'rails_helper'

RSpec.describe ApplicationCable::Connection, type: :channel do
  let(:user) { create(:user) }

  before do
    stub_connection(current_user: user)
  end

  it 'successfully connects' do
    expect { connect '/cable' }.to_not raise_error
  end
end

但出现错误:

ApplicationCable::Connection
current_user:
nil
  successfully connects (FAILED - 1)

Failures:

  1) ApplicationCable::Connection successfully connects
     Failure/Error: expect { connect '/cable' }.to_not raise_error

       expected no Exception, got #<NoMethodError: undefined method `[]' for nil:NilClass> with backtrace:
         # ./app/channels/application_cable/connection.rb:19:in `find_verified_user'
         # ./app/channels/application_cable/connection.rb:8:in `connect'
         # /home/user/.rvm/gems/ruby-2.4.1/gems/action-cable-testing-0.3.1/lib/action_cable/connection/test_case.rb:176:in `connect'
         # ./spec/channels/user_channel_spec.rb:11:in `block (3 levels) in <top (required)>'
         # ./spec/channels/user_channel_spec.rb:11:in `block (2 levels) in <top (required)>'
     # ./spec/channels/user_channel_spec.rb:11:in `block (2 levels) in <top (required)>'

所以我有两个问题:

  1. 为什么 current_usernil
  2. 如何对用户进行身份验证?

最佳答案

如果您想使用current_user 设置测试连接,您应该 stub env['warden'],如此处所示https://stackoverflow.com/a/53841098/7121891

如果要测试 Channel 类,请使用 action-cable-testing已经集成到 Rails 6 中的 gem

关于ruby-on-rails - 如何使用 rspec 测试 ActionCable 和 Devise?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50549428/

相关文章:

ruby-on-rails - 为什么 Rails 在我 `include` 模块时尝试猜测文件名?

mysql - Rails 4 - 如何将 "includes(:model)"与 ".select(...)"一起使用?还有其他选择吗?

ruby - Ruby 测试的图形用户可视化

ruby-on-rails - 如何在 Controller RSpec 中测试设计,错误:未定义方法 `assign' for #<RSpec::Core::ExampleGroup::Nested_1:0x0000010597f4b8>

ruby-on-rails - 不允许的参数 : user_id error in rails

ruby-on-rails - 无法使用 Devise 获取新的 Rails 应用程序以显示 sign_in/sign_up 页面

ruby-on-rails - Rails 3 - lib 未初始化常量 ActionView::CompiledTemplates::STATES

ruby-on-rails - RSpec 测试卡在新机器 OSX 上

ruby-on-rails - 如何在RSpec中使用HTTP状态代码符号?

ruby-on-rails - 搜索表单未路由到 Rails 5.1 中的正确 Controller