【问题标题】:Sending a real JSON post request from RSpec从 RSpec 发送真正的 JSON 发布请求
【发布时间】:2017-09-20 08:52:00
【问题描述】:

我希望能够为端点响应测试远程 3d 方 API,这就是为什么我想编写一堆本地 rspec 测试并定期启动它们,以查看这些端点是否按预期工作没有重大变化。由于我的应用程序高度依赖于这个不断变化的 API,我别无选择,只能自动化我的测试。

目前我拿了一个常规的rspec API测试代码:

require "rails_helper"

RSpec.describe "Remote request", type: :request do
  describe ".send request" do
    it ".posts valid data" do
      post "http://123.45.67.89/api/endpoint",
        params: {
                  "job_request_id": 123456,
                  "data": "12345",
                  "app_secret": "12345",
                  "options": {
                     ...
                  }
                }

      expect(JSON.parse response.body).to include("message" => "success")
      expect(response).to have_http_status(200)
    end
  end
end

此代码的问题在于 Rspec 访问的是 /api/endpoint url,而不是完整的 http://123.45.67.89/api/endpoint url。我该如何改变这种行为?

【问题讨论】:

    标签: ruby-on-rails rspec


    【解决方案1】:

    RSpec 的请求规范旨在通过发送真实的 HTTP 请求来测试您自己的应用程序。它们不适用于执行远程 HTTP 请求(即使配置猴子可以请求除 localhost 之外的其他主机)。

    除其他事项外,每个示例的请求规范都会命中 API - 这会给您带来速率限制和节流问题。

    虽然您可以尝试在请求规范中使用像 Net::HTTPHttpartyTyphoeus 这样的 HTTP 库,但您真正应该做的是重新考虑您的方法。隔离您的应用程序和外部协作者之间的交互是一个好主意。

    一种方法是创建使用远程 API 的客户端类:

    class ExampleAPIClient
      include HTTParty
      base_url 'example.com'
      format :json
    
      def get_some_data
        self.class.get('/foo')
      end
    end
    

    然后您可以通过像普通旧 Ruby 对象一样测试客户端来测试远程端点:

    require 'spec_helper'
    RSpec.describe ExampleAPIClient do
      let(:client) { described_class.new }
    
      describe "#get_some_data" do
        let(:response) { client.get_some_data }
        it "should be successful" do
          expect(response.success?).to be_truthy
        end 
      end
    end
    

    这将具有限制应用程序更改的额外好处,因为如果远程 api 更改,只有单个组件(客户端)会失败。

    使用客户端的其他组件可以通过存根客户端轻松地存根远程交互。

    【讨论】:

      猜你喜欢
      • 2018-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-31
      • 1970-01-01
      相关资源
      最近更新 更多