如何为Rails 6中的Action Cable连接类编写单元测试?

huangapple go评论59阅读模式
英文:

How can I write unit tescase for action cable connection class in rails 6

问题

以下是我的connection.rb

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
      verified_user = env['warden'].user
      return verified_user if verified_user
    end
  end
end

我如何在环境变量 warden 上进行单元测试?
我需要设置它吗?

英文:

> following is my connection.rb

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
      verified_user = env['warden'].user
      return verified_user if verified_user
    end
  end
end

> How can I work on a unit test with the environment variable warden?
> Do I need to set it?

答案1

得分: 1

在经过了大量搜索之后,我找到了解决方案,适用于connection_test.rb文件:

# frozen_string_literal: true

require "test_helper"

module ApplicationCable
  class ConnectionTest < ActionCable::Connection::TestCase
    include ActionCable::TestHelper

    test "connects with devise" do
      user = users(:admin)
      connect_with_user(user)
      assert_equal connection.current_user, user
    end

    private

    def connect_with_user(user)
      connect env: { 'warden' => FakeEnv.new(user) }
    end

    class FakeEnv
      attr_reader :user

      def initialize(user)
        @user = user
      end
    end
  end
end

请注意,这只是提供了代码的翻译部分,不包含其他内容。

英文:

> after too much of search I have got the solution for connection_test.rb

# frozen_string_literal: true

require &quot;test_helper&quot;

module ApplicationCable
  class ConnectionTest &lt; ActionCable::Connection::TestCase
    include ActionCable::TestHelper

    test &quot;connects with devise&quot; do
      user = users(:admin)
      connect_with_user(user)
      assert_equal connection.current_user, user
    end

    private

    def connect_with_user(user)
      connect env: { &#39;warden&#39; =&gt; FakeEnv.new(user) }
    end

    class FakeEnv
      attr_reader :user

      def initialize(user)
        @user = user
      end
    end
  end
end

huangapple
  • 本文由 发表于 2020年1月3日 15:15:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/59574578.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定