Testing an external API using RSpec's request specs

只愿长相守 提交于 2019-12-07 17:47:45

问题


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.

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


回答1:


Yes, it's possible

Basically

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.

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

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.



来源:https://stackoverflow.com/questions/18364076/testing-an-external-api-using-rspecs-request-specs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!