使用RSpec的请求规范测试外部API

Mad*_*han 3 ruby rspec ruby-on-rails rspec-rails

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

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

Bil*_*han 5

是的,这是可能的

基本上

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

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

然后你可以使用像Fakeweb或类似的模拟宝石: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
Run Code Online (Sandbox Code Playgroud)

你获得正常的html响应或jsonp响应并不重要.全部相似.

以上是低级方式.更好的方法是使用应用程序中的代码进行检查.但是你最终总是需要嘲笑.