【问题标题】:How to use webmock to simulate a request?如何使用 webmock 模拟请求?
【发布时间】:2020-03-12 19:12:52
【问题描述】:

我的应用程序使用 API 创建了一个 github gist。我需要使用 rspec 模拟对 API 的请求。我正在使用 webmock gem,但我不太明白如何将它用于我的应用程序。我需要一点帮助才能开始。

这是我的 spec/Git_Request_spec.rb

require_relative '../Gist_Request.rb'
require 'spec_helper'

RSpec.describe GistRequest do
  describe "#post" do
    it "crear gist" do
      filename = "test.txt"
      description = "descripción"
      state = true
      content = "contenido"

      gist_create = GistRequest.new(description, state, filename, content)
      gist_create.post()

      expect(gist_create.response_status).to eq "201"
    end

    it "campos no válidos" do
      filename = "test.txt"
      description = "descripción"
      state = true
      content = "contenido"

      gist_create = GistRequest.new(filename, content, state, description)
      gist_create.post()

      expect(gist_create.response_status).to eq "422"
   end
 end
end

有什么想法吗?

【问题讨论】:

  • 一旦你调用了Webmock.enable!(参见github.com/bblimke/webmock),无论何时你从你的测试Webmock发出请求都会导致它出错,并且会给出如何模拟该请求的说明。跨度>
  • 我应该在 Gist_Request_spec.rb 中给他打电话吗?

标签: ruby rspec webmock


【解决方案1】:

你需要使用方法stub_request来模拟你与api的交互

stub_request(:http_method, url).with(`your data in 
request`).to_return(`what do you expect to receive in response`).

【讨论】:

  • 喜欢这个? stub_request(:http_method, url).with(gist_create.response_status).to_return("201") 对我不起作用:WebMock::NetConnectNotAllowedError: Real HTTP connections are disabled. Unregistered request: POST .......
猜你喜欢
  • 1970-01-01
  • 2021-10-02
  • 2016-11-27
  • 1970-01-01
  • 1970-01-01
  • 2013-02-28
  • 2015-04-29
  • 1970-01-01
  • 2019-11-14
相关资源
最近更新 更多