如何在控制器范围之外使用 Ministest / TestCase 测试外部请求

How to test external request with Ministest / TestCase out of controller scope

我是 Minitest 的新手,目前一切正常,因为它并不难学,但是,我坚持进行例行测试:测试将文件上传到 S3 的控制器。

目标: 进行一个测试,用它的文件创建一个新的 Person.create() 对象,在本例中是一个带有一些图像的 zip。

上下文:

我的问题是我在 Google 和 Whosebug 中尝试了很多搜索方法,但我不确定如何在 Controller 范围之外解决此测试。

require 'test_helper'
  require 'webmock/minitest'

  class PersonPhotosUpdateTest < ActiveSupport::TestCase
    def setup
      # some setup here
    end

    describe "My tests" do
      test "Upload a zip file for Person" do 
        # My test here
      end
    end
  end

我想参加考试:

我想我需要模拟 and/or 存根,但我不确定如何使用 Minitest。

谢谢。

您可能想要创建一个 integration test:

require 'test_helper'
require 'webmock/minitest'

class LocationImporterTest < ActionDispatch::IntegrationTest
  before do
    stub_request(:any, "https://s3.amazonaws.com")
  end

  test "create" do
    post "/foo", { 
      # params...
    }

    assert_requested :post, "https://s3.amazonaws.com",
      :headers => {'Content-Length' => 3}, 
       :body => "abc",
      :times => 1    # ===> Success
  end
end

请参阅 webmock documents 以了解如何在 HTTP 请求上设置期望值,请注意 Test/Unit 和 Minitest 可以互换。