【问题标题】:How to write a remote request spec?如何编写远程请求规范?
【发布时间】:2023-03-04 15:39:01
【问题描述】:

我的 Rails 应用程序中有一个动作,它以 html 和 js 格式响应。 结果,根据格式,有点变化。因此,我想为 html 编写一个测试,为 js 响应编写另一个测试。 我正在使用 rspec。

控制器:

# app/controllers/my_controller.rb
class MyController < ApplicationController
  def my_action
    respond_to do |format|
      format.html do
        # Do something...
      end

      format.js do
        # Do something else...
      end
    end
  end
end

规格:

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

RSpec.describe "My", type: :request do
  describe "GET /my_action" do
    context 'HTML' do
      # HTML tests
    end

    context 'JS' do
      # JS tests
    end
  end
end

【问题讨论】:

  • 是的,你就是这样做的。我不明白你的问题是什么。
  • 问题是我不知道如何在rspec中触发一个js请求。
  • 以.js结束网址
  • 一定是get my_action_path, format: :js
  • 您正在寻找这个答案:stackoverflow.com/a/44680041/1930295

标签: ruby-on-rails rspec ruby-on-rails-6


【解决方案1】:

Rails 通过 http Accept 标头检测请求格式,在测试中有一个用于模拟 xhr 的助手(还设置了 X-Requested-With,这是缓解 CSRF 的一部分):

get "/some/path/to/my_action", xhr: true

【讨论】:

    猜你喜欢
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    相关资源
    最近更新 更多