【问题标题】:Mini mock server for rspec without rails没有导轨的 rspec 迷你模拟服务器
【发布时间】:2022-01-08 18:59:28
【问题描述】:

我想在 rspec 中测试一个 API 客户端。

我目前正在嘲笑 Typhoeus - 但我想知道是否有更端到端的方式来做到这一点。本质上,我想要的是这样的:

it "makes a connection to the server" do
  MockServer.new do |server|
    subject.url = server.url
    subject.run!

    expect(server.last_request.params).to eq({some: "params"})
    expect(server.last_request.headers).to include({"X-whatty-what" => "yepyep"})
  end
end

也许我可以用 Sinatra 做到这一点,甚至可以直接使用 rack...以前有人做过类似的事情吗?

【问题讨论】:

    标签: ruby rspec minitest end-to-end


    【解决方案1】:

    使用Webmock 存根请求。

    建议对您希望单独发出的每个请求进行存根,以便您确切知道请求的内容,但您也可以使用与您所要求的类似的语法。

    it "makes a connection to the server" do
      stub_request(:any, "www.example.com")
    
      subject.url = "www.example.com"
      subject.run!
    
      expect(
        a_request(:post, "www.example.com").with(
          body: { some: "params" },
          headers: { "X-whatty-what" => "yepyep" }
        )
      ).to have_been_made
    end
    

    webmock 文档有很多很好的例子,看看吧。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-18
      • 2011-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多