2013-08-21 51 views
2

我正在尝试使用RSpec的请求规范将主机更改为指向远程URL而不是localhost:3000。请让我知道这是否可能。使用RSpec的请求规范测试外部API

注意:只想提及远程URL只是一个JSON API。

+0

也许你想要这个:http://stackoverflow.com/questions/12219085/can-i-use-rspec-to-test-deployed-site –

回答

5

是的,这是可能的

基本上

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

但是你可能需要模拟响应,测试最好不要依赖于外部资源。

然后你可以使用模拟的宝石一样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 

不要紧,你会得到一个正常的HTML响应或JSONP响应。所有相似。

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

+0

嘿比利,而不是这是有办法设置默认主机到“www.google.com”,这样我的所有请求规格/用户都会针对该主机运行? – Madhan

+0

@MadhanPadmanabhan,这应该是你想要的。您可以将google.com设置为变量并分别设置查询字符串。在这里检查:http://ruby-doc.org/stdlib-2.0/libdoc/net/http/rdoc/Net/HTTP.html#label-GET+with+Dynamic+Parameters –

+0

嗯,我得到未初始化的常量净: :甚至当我需要Http时:/ – Madhan

相关问题