2011-05-02 118 views
21

我使用Savon gem來使用類似於下面的代碼的SOAP請求。它正在工作,但我希望查看/捕獲請求XML,而無需實際調用其服務器。通過在請求後面粘貼調試器行並檢查客戶端變量,我可以在請求發出後立即查看它。查看Savon請求XML而不發送到服務器

有沒有人知道的方式來查看請求的XML沒有實際提出請求?我希望能夠使用Cucumber或Rspec驗證XML模式。

client = Savon::Client.new do |wsdl, http| 
    wsdl.document = "http://fakesite.org/fake.asmx?wsdl" 
end 

client.request(:testpostdata, :xmlns => "http://fakesite.org/") do 
    soap.header = { :cAuthentication => {"UserName" => "MyName", "Password" => "MyPassword" } } 
    soap.body = { :xml_data => to_xml } 
end 

回答

7

Savon使用HTTPI執行SOAP請求。 HTTPI是各種Ruby HTTP客戶端的通用接口。你也許可以模擬/存根通​​過由薩翁執行HTTP請求:

HTTPI.expects(:post).with do |http| 
    SchemaValidation.validate(:get_user, http.body) 
end 

請注意,我用Mocha用於嘲諷的SOAP請求,得到了HTTP身體和驗證它針對一些驗證方法(僞代碼)。

目前,Savon不支持在不執行它們的情況下構建請求。所以驗證請求的唯一方法是攔截它。

如果您需要Savon支持此功能,請告訴我,open a ticket over at GitHub

編輯:還有savon_spec,這是一個基本的與薩貢基於夾具測試的小幫手。

+0

感謝您的建議。我可以沒有這個功能,只想知道它是否可能。 – 2011-05-03 14:55:50

10

雖然我確定有更好的方法來做到這一點,但我只是否定了迴應。

class Savon::SOAP::Request 
    def response 
    pp self.request.headers 
    puts 
    puts self.request.body 
    exit 
    end 
end 
+0

這是幫助調試的便宜且簡單的方法。謝謝。 – 2011-11-03 13:32:05

+0

如果我想要這個,但也發送請求到服務器呢? – Fakada 2013-07-01 12:20:00

+0

@Fakada'super' – 2014-03-26 03:42:43

8

他們已經更新了自上一篇文章以來的API。在Savon.client::pretty_print_xml => true中設置此設置。在您的通話之後,搜索日誌中的SOAP請求:。輸出被放到標準輸出。如果您要從控制檯測試連接,請檢查控制檯控制檯歷史記錄。

5

我有同樣的問題,並修補薩翁如下:

module Savon 
    class Client 
    def get_request_xml operation_name, locals 
     Savon::Builder.new(operation_name, @wsdl, @globals, locals).pretty 
    end 
    end 
end 

這將生成XML,並返回一個字符串,而不把它發送到API端點。它不像client.call那樣接受block參數,所以它不能重現你所做的每一種請求,但它現在滿足了我的需求。

34

使用Savon 2我這樣做,寫一個方法,從客戶端返回請求體。

client = Savon::Client.new(....) 

這不是

def get_request 
    # list of operations can be found using client.operations 
    ops = client.operation(:action_name_here) 

    # build the body of the xml inside the message here   
    ops.build(message: { id: 42, name: "Test User", age: 20 }).to_s 
    end 
+0

'.pretty'使身體更易於閱讀 – akz92 2017-09-04 11:33:23

+0

(用'pretty'替換'to_s') – 2018-01-24 19:00:05

9

我使用薩翁2.11文檔中提到的,我可以在客戶端與全局完成它:

def client 
    @client ||= Savon.client(soap_version: 2, 
          wsdl:   config.wsdl, 
          logger:  Rails.logger, 
          log:   true) 
end 

More info on the globals here.

然後記錄器吐出主機,http動詞和完整的xml(「headers」和bo dy)的請求和響應。

11

您可以直接通過Savon::Client#build_request方法。

例子:

request = client.build_request(:some_operation, some_payload) 
request.body # Get the request body 
request.headers # Get the request headers 

以峯值@https://github.com/savonrb/savon/blob/master/lib/savon/request.rb爲全面文檔。

+0

這應該是正確的答案,因爲它是最直接的,並且使用Savon而不必修改任何部分的。 – codeshaman 2017-05-22 18:51:12