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

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

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

问题

以下是我的connection.rb

  1. module ApplicationCable
  2. class Connection < ActionCable::Connection::Base
  3. identified_by :current_user
  4. def connect
  5. self.current_user = find_verified_user
  6. end
  7. private
  8. def find_verified_user
  9. verified_user = env['warden'].user
  10. return verified_user if verified_user
  11. end
  12. end
  13. end

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

英文:

> following is my connection.rb

  1. module ApplicationCable
  2. class Connection < ActionCable::Connection::Base
  3. identified_by :current_user
  4. def connect
  5. self.current_user = find_verified_user
  6. end
  7. private
  8. def find_verified_user
  9. verified_user = env['warden'].user
  10. return verified_user if verified_user
  11. end
  12. end
  13. 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文件:

  1. # frozen_string_literal: true
  2. require "test_helper"
  3. module ApplicationCable
  4. class ConnectionTest < ActionCable::Connection::TestCase
  5. include ActionCable::TestHelper
  6. test "connects with devise" do
  7. user = users(:admin)
  8. connect_with_user(user)
  9. assert_equal connection.current_user, user
  10. end
  11. private
  12. def connect_with_user(user)
  13. connect env: { 'warden' => FakeEnv.new(user) }
  14. end
  15. class FakeEnv
  16. attr_reader :user
  17. def initialize(user)
  18. @user = user
  19. end
  20. end
  21. end
  22. end

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

英文:

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

  1. # frozen_string_literal: true
  2. require &quot;test_helper&quot;
  3. module ApplicationCable
  4. class ConnectionTest &lt; ActionCable::Connection::TestCase
  5. include ActionCable::TestHelper
  6. test &quot;connects with devise&quot; do
  7. user = users(:admin)
  8. connect_with_user(user)
  9. assert_equal connection.current_user, user
  10. end
  11. private
  12. def connect_with_user(user)
  13. connect env: { &#39;warden&#39; =&gt; FakeEnv.new(user) }
  14. end
  15. class FakeEnv
  16. attr_reader :user
  17. def initialize(user)
  18. @user = user
  19. end
  20. end
  21. end
  22. 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:

确定