使用 Rspec 测试 Turbo 流操作

问题描述 投票:0回答:2

我正在对使用涡轮流的控制器操作进行 rspec 测试:

  describe 'GET /CONTROLLER_NAME' do

    it 'return a turbo stream answer' do
      get :index, as: :turbo_stream
      expect(response).to eq Mime[:turbo_stream]
    end
  end

end

Failure/Error: expect(response).to eq Mime[:turbo_stream]

       expected: #<Mime::Type:0x00007f7d9c2e1ff0 @synonyms=[], @symbol=:turbo_stream, @string="text/vnd.turbo-stream.html", @hash=2866392594387537360>
            got: #<ActionDispatch::TestResponse:0x00007f7d976945f8 @mon_data=#<Monitor:0x00007f7d97694580>, @mon_data_...oller::TestRequest GET "http://test.host/CONTROLLER_NAME.turbo_stream" for 0.0.0.0>>

如何在控制器测试中使用 Turbo Stream 进行 get 查询?

ruby-on-rails rspec turbo
2个回答
12
投票

您应该检查

response.media_type
Mime[:turbo_stream]
而不是仅仅
request
。检查涡轮流测试助手

  describe 'GET /CONTROLLER_NAME' do
    it 'return a turbo stream answer' do
      get :index, as: :turbo_stream
      expect(response.media_type).to eq Mime[:turbo_stream]
    end
  end


0
投票

我建议转向请求测试,因为控制器测试已被弃用,这是一个示例,我想:

# spec/controllers/patients_controller_spec.rb
require "rails_helper"

RSpec.describe PatientsController, type: :controller do      
  describe "GET /patients" do
    it "returns patients list" do
      get :index, as: :turbo_stream
      expect(response).to have_http_status(:ok)
    end
  end
end

这是请求测试,仅供将来参考:

# spec/requests/patients_spec.rb
require "rails_helper"

RSpec.describe "patients", type: :request do      
  describe "GET /patients" do
    it "returns patients list" do
      get patients_path(format: :turbo_stream)
      expect(response).to have_http_status(:ok)
    end
  end
end

您还可以访问某些响应的属性,例如response.status、response.content_type

我不拥有这些链接,但可以帮助您找到正确的断言:

© www.soinside.com 2019 - 2024. All rights reserved.