2013-08-21 113 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

相關問題