2

Rails モデルの 1 つでメソッドをテストしようとしています。URL から HTTP ステータスを返していますが、コードがさまざまな状況で機能することを確認するために、さまざまなリターン コードをテストするためにリターンをスタブする方法がわかりません。

モックしたいコード行は次のとおりです。

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 からの戻り値をスタブ化するにはどうすればよいですか?

4

1 に答える 1

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"])
于 2012-09-14T02:52:41.790 に答える