如何编写远程请求规范?

How to write a remote request spec?

我的 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

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

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