2012-09-14 22 views
2

我試圖測試一個方法,我有我的軌道模型之一。我從一個url返回HTTP狀態,不知道如何存根返回來測試不同的返回碼,以確保我的代碼適用於不同的情況。測試網:: HTTP.get_Response()

這是我想嘲弄的代碼行:

response = Net::HTTP.get_response(URI.parse(self.url)) 

我想有Net:HTTP.get_response返回一個特定的類HTTPResponse每個我在規範的測試。

describe Site do 
    before :each do 
    FactoryGirl.build :site 
    end 
    context "checking site status" do 
    it "should be true when 200" do 
     c = FactoryGirl.build :site, url:"http://www.example.com/value.html" 
     #something to mock the Net::HTTP.get_response to return and instance of Net::HTTPOK 
     c.ping.should == true 
    end  
    it "should be false when 404" do 
     c = FactoryGirl.build :site, url:"http://www.example.com/value.html" 
     #something to mock the Net::HTTP.get_response to return and instance of Net::HTTPNotFound 
     c.ping.should == false  
    end 
    end 
end 

如何從get_response中存取返回值?

回答

3

我建議fakeweb爲此,例如:

FakeWeb.register_uri(:get, 
    "http://example.com/value.html", 
    :body => "Success!") 

FakeWeb.register_uri(:get, 
    "http://example.com/value.html", 
    :body => "Not found!", 
    :status => ["404", "Not Found"])