have_stream_from
匹配器
have_stream_from
匹配器用于检查通道是否已订阅给定流,该流以字符串形式指定。如果您在通道中使用 stream_for
来订阅模型,请使用 have_stream_for
匹配器。
have_no_streams
匹配器用于检查通道是否未订阅任何流。
它仅在通道规格中可用。
背景
鉴于 可用动作电缆测试
以及 一个名为“app/channels/chat_channel.rb”的文件,其中包含
class ChatChannel < ApplicationCable::Channel
def subscribed
reject unless params[:room_id].present?
stream_from "chat_#{params[:room_id]}"
end
def leave
stop_all_streams
end
end
使用参数订阅并检查流
鉴于 一个名为“spec/channels/chat_channel_spec.rb”的文件,其中包含
require "rails_helper"
RSpec.describe ChatChannel, type: :channel do
it "successfully subscribes" do
subscribe room_id: 42
expect(subscription).to be_confirmed
expect(subscription).to have_stream_from("chat_42")
end
end
当 我运行 rspec spec/channels/chat_channel_spec.rb
则 示例应通过。
停止所有流
鉴于 一个名为“spec/channels/chat_channel_spec.rb”的文件,其中包含
require "rails_helper"
RSpec.describe ChatChannel, type: :channel do
it "successfully subscribes" do
subscribe(room_id: 42)
expect(subscription).to have_stream_from("chat_42")
perform :leave
expect(subscription).not_to have_streams
end
end
当 我运行 rspec spec/channels/chat_channel_spec.rb
则 示例应通过。
订阅模型并检查流
鉴于 一个名为“app/channels/notifications_channel.rb”的文件,其中包含
class NotificationsChannel < ApplicationCable::Channel
def subscribed
stream_for current_user
end
end
以及 一个名为“app/channels/application_cable/connection.rb”的文件,其中包含
class ApplicationCable::Connection < ActionCable::Connection::Base
identified_by :current_user
end
以及 一个名为“app/models/user.rb”的文件,其中包含
class User < Struct.new(:name)
def to_gid_param
name
end
end
以及 一个名为“spec/channels/user_channel_spec.rb”的文件,其中包含
require "rails_helper"
RSpec.describe NotificationsChannel, type: :channel do
it "successfully subscribes to user's stream" do
stub_connection current_user: User.new(42)
subscribe
expect(subscription).to be_confirmed
expect(subscription).to have_stream_for(User.new(42))
end
end
当 我运行 rspec spec/channels/user_channel_spec.rb
则 示例应通过。