使用 RSpec 的请求规范测试外部 API [英] Testing an external API using RSpec's request specs

查看:49
本文介绍了使用 RSpec 的请求规范测试外部 API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 RSpec 的请求规范将主机更改为指向远程 URL 而不是 localhost:3000.如果可行,请告诉我.

I am trying to use RSpec's request specs to change the host to point to a remote URL instead of localhost:3000. Please let me know if this is possible.

注意:只是想提一下远程 URL 只是一个 JSON API.

Note: Just wanted to mention that the remote URL is just a JSON API.

推荐答案

是的,这是可能的

基本上

require 'net/http'
Net::HTTP.get(URI.parse('http://www.google.com'))
# => Google homepage html

但您可能需要模拟响应,因为测试最好不要依赖外部资源.

But you may need to mock the response as tests are better not to depend on external resource.

然后你可以使用像 Fakeweb 或类似的模拟 gem:https://github.com/chrisk/fakeweb

Then you can use mock gems like Fakeweb or similar: https://github.com/chrisk/fakeweb

require 'net/http'
require 'fakeweb'
FakeWeb.register_uri(:get, "http://www.google.com", :body => "Hello World!")

describe "external site" do
  it "returns 'World' by visiting Google" do
    result = Net::HTTP.get(URI.parse('http://www.google.com'))
    result.should match("World")
    #=> true
  end
end

你得到一个普通的 html 响应还是 jsonp 响应都没有关系.都差不多.

It doesn't matter you get a normal html response or jsonp response. All similar.

以上是低级方式.更好的方法是在应用程序中使用您的代码来检查它.但你最终总是需要模拟.

The above is low level way. The better way is to use your code in app to check it. But you'll always need mock finally.

这篇关于使用 RSpec 的请求规范测试外部 API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆