使用RSpec的请求规范测试外部API
我正在尝试使用RSpec的请求规范将主机更改为指向远程URL而不是localhost:3000。 如果可能,请告诉我。
注意:只是想提一下远程URL只是一个JSON API。
是的,这是可能的
基本上
require 'net/http' Net::HTTP.get(URI.parse('http://www.google.com')) # => Google homepage html
但是您可能需要模拟响应,因为测试最好不依赖于外部资源。
然后你可以使用像Fakeweb或类似的模拟gem: 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响应并不重要。 全部相似。
以上是低级方式。 更好的方法是在应用程序中使用您的代码进行检查。 但是你最终总是需要嘲笑。