'get or post within ActionCable tests in Rails 6?
I am using a JWT to authenticate my user.
So when a user want to connect to the ActionCable server, it does something like this:
- Get a JWT from REST endpoint: POST /users/sign_in
- Establish a ws to ActionCable using this jwt.
// Establish connection
ws = new WebSocket("ws://localhost:3000/websocket?token="+jwt)
I want to test this connection so I'm using what is in Rails 6 out of the box:
# 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: "[email protected]", password: "ok"}}, as: :json
    token  = response.headers["Authorization"]
    connect params: { token: token }
    assert_equal connection.user_id, "1"
  end
end
But i have the following error:
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>
What should I do to be able to perform this post to my controller ?
Thanks!
BONUS: if I can use routes prefixes, i.e. user_session_url instead of "/users/sign_in" it's better!
Solution 1:[1]
You can pull in all of the ActionDispatch::IntegrationTest goodies by including ActionDispatch::IntegrationTest::Behavior in your test class.
I haven't tested this with ActionCable::Connection::TestCase, but I'm using it with my channel tests like this:
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|---|
| Solution 1 | Jenner La Fave | 
