2012-11-08 36 views
3

我正在使用rspec和capybara編寫測試用例,以便與Cheddargetter(付款解決方案提供商)集成。我沒有問題測試我的CG API的請求,但我不知道如何最好地測試CG的API給Web應用程序的回調。如何測試webhooks /遠程回調?

這與PayPal的IPN功能類似,客戶支付Web鉤子回調後發送到您的應用程序。

想知道是否有人知道什麼是測試/模擬這個最好的方法?

回答

3

你可能使用的是控制器來處理POST請求,讓我們把它WebhookController

你可以簡單地測試與你所需要的PARAMS後做你想要什麼。例如,我整合測試(在測試單位但rspec做同樣的事情)。

Rspec對於上傳/添加xml文件可能有不同版本的fixture_file_upload,但according to this stack question看起來您也可以使用它。堅持檔案說spec/files

無論如何,對於網絡和新手來說,你會測試你的Delayed::Job調用實際上在另一個測試中有效。 喜歡的東西:


class GetWebhookTest < ActionController::IntegrationTest 
    fixtures :all 
    def recieve_webhook 
    post '/webhook/338782', fixture_file_upload('webhook.xml', 'application/xml') 
    end 
    #Test you do what the outcome of your POST would be. 
    #this is refactored but you can shove the post line where receive_webhook is 
    test "recieve a webhook via xml" do 
    assert_difference('RawData.count') do 
     receive_webhook 
    end 
    end 

    test "make sure the status is 200" do 
    recieve_webhook 
    assert_response :success 
    end 
    #Test 1 will fail before this, but i was more/too thorough back in the day 
    test "Delayed Job increases" do 
    assert_difference "Delayed::Job.count", 1 do 
     recieve_webhook 
    end 
    end 
end 

再次,Rspec的有之類的東西response.should be_success及其Object.count差分法了。根據你的情況調整。關鍵是fixture_file_upload

+0

這看起來像是一個很好的方法。任何現有的寶石可以幫助進行這種測試嗎?尤其是爲了幫助保存現有的POST請求並將其存儲到文件以便稍後重用(如VCR,但用於回調而不是請求) – redshift5

+0

我想你想在'postbin'中記錄實際的呼叫(我認爲服務是所謂的)。就像這個http://requestb.in/,你會得到你需要的xml。之後,它是fixture_file_upload和真正的測試。我見過的大多數寶石都是外發的,而不是傳入的,這就是fixture_file_upload的作用。海事組織。 – pjammer

+0

謝謝,雖然requestb.in服務似乎因爲某些原因被打破。如果我在Web控制檯中檢查AJAX調用,會出現500內部錯誤。我甚至檢出並將自己的版本部署到Heroku,並具有相同的問題。我會尋找替代服務。你能想到另一個頭腦嗎?謝謝你的方式 – redshift5