我正在使用JWT对我的用户进行身份验证。
因此,当用户想要连接到ActionCable服务器时,它会执行以下操作:
- 从REST端点获取JWT:POST/users/sign_in
- 使用这个jwt建立一个ws-to-ActionCable
// Establish connection
ws = new WebSocket("ws://localhost:3000/websocket?token="+jwt)
我想测试这个连接,所以我使用Rails 6中开箱即用的东西:
# test/channels/application_cable/connection_test.rb
require "test_helper"
class ApplicationCable::ConnectionTest < ActionCable::Connection::TestCase
test "connects with jwt" do
post "/users/sign_in", params: { user: {email: "123@ok.com", password: "ok"}}, as: :json
token = response.headers["Authorization"]
connect params: { token: token }
assert_equal connection.user_id, "1"
end
end
但我有以下错误:
Error:
ApplicationCable::ConnectionTest#test_connects_with_jwt:
NoMethodError: undefined method `post' for #<ApplicationCable::ConnectionTest:0x0000555bbab0ecb0>
test/channels/application_cable/connection_test.rb:6:in `block in <class:ConnectionTest>
我应该做些什么才能对我的控制器执行此post
?谢谢
奖金:如果我可以使用路由前缀,即user_session_url
而不是"/users/sign_in"
,那就更好了!
您可以通过在测试类中包含ActionDispatch::IntegrationTest::Behavior
来获取所有的ActionDispatch::IntegrationTest
好东西。
我还没有用ActionCable::Connection::TestCase
测试过这一点,但我正在把它和我的通道测试一起使用,比如:
require "test_helper"
class FoosChannelTest < ActionCable::Channel::TestCase
include ActionDispatch::IntegrationTest::Behavior
tests FoosChannel
let(:user) { create(:user) }
describe "when a new Foo is created" do
it "broadcasts an event to the user channel" do
post foos_path, params: {
foo: {
name: "Foo1",
}
}, as: :json
assert_broadcasts user, 1
end
end
end
我使用了这个https://relishapp.com/palkan/action-cable-testing/docs(相同的代码可用于请求规范(
RSpec.describe CommentsController do
describe "POST #create" do
expect { post :create, comment: { text: 'Cool!' } }.to
have_broadcasted_to("comments").with(text: 'Cool!')
end
end
不要忘记禁用后台作业(如果作业延迟,请添加Delayed::Worker.delay_jobs = false
(