如何在RubyMine日志中验证Savon响应并终止错误测试?
解决方案:验证SOAP响应内容并在错误时终止测试
首先,你完全不需要依赖RubyMine的事件日志来验证SOAP响应——Savon本身会返回包含完整响应数据的对象,直接用这个对象来处理是最可靠、最易维护的方式。下面分两部分解决你的问题:
一、验证SOAP响应中的内容
在你的Cucumber步骤中,先捕获Savon调用的返回结果,然后将其转换为Ruby哈希(方便访问内部字段),再添加断言验证你需要的内容。
1. 修改步骤定义保存响应
首先,把call方法的返回值存到实例变量中,方便后续步骤访问:
And(/^I send the SOAP call 'close collection'$/) do @soap_response = $soap_client_pymntmgr.call(:close_collection, message: { :"sch:collectionGroupId" => $group_id, :attributes! => { collectionGroupId: { 'xmlns' => 'http://test.com/requests/payment-manager/schema'}} }) end
2. 添加验证步骤
用RSpec的断言(Cucumber默认支持)来验证响应中的success状态和错误信息:
# 验证响应是否成功 Then(/^the SOAP call should succeed$/) do # 将响应转换为哈希,Savon会自动把XML标签转为蛇形命名的键 response_hash = @soap_response.to_hash # 注意键名要和XML响应对应:<checkCollectionGroupResponse> → :check_collection_group_response response_body = response_hash[:check_collection_group_response] # 验证success字段为true(注意这里可能是字符串或布尔值,根据实际返回调整) expect(response_body[:success]).to eq('true') end # 验证特定错误信息 Then(/^the SOAP response should return error code (\d+) with message "(.*?)"$/) do |error_code, expected_message| response_hash = @soap_response.to_hash response_body = response_hash[:check_collection_group_response] error_details = response_body[:error] expect(error_details[:code]).to eq(error_code) expect(error_details[:message]).to eq(expected_message) end
二、响应包含错误时终止测试
如果希望在SOAP调用返回错误时直接终止测试(让测试失败),可以在调用后立即检查响应,一旦发现错误就抛出异常:
And(/^I send the SOAP call 'close collection'$/) do @soap_response = $soap_client_pymntmgr.call(:close_collection, message: { :"sch:collectionGroupId" => $group_id, :attributes! => { collectionGroupId: { 'xmlns' => 'http://test.com/requests/payment-manager/schema'}} }) response_hash = @soap_response.to_hash response_body = response_hash[:check_collection_group_response] # 检查success状态或是否存在error标签 if response_body[:success] == 'false' || response_body.key?(:error) error_code = response_body[:error][:code] error_msg = response_body[:error][:message] # 抛出异常会直接让Cucumber测试失败并终止后续步骤 raise "SOAP call 'close collection' failed: Error #{error_code} - #{error_msg}" end end
小提示
- Savon的
to_hash方法会自动将XML的驼峰命名标签转换为Ruby风格的蛇形命名(比如<checkCollectionGroupResponse>→:check_collection_group_response),如果不确定键名,可以用puts response_hash.inspect打印出来查看。 - 不要依赖解析日志文本的方式来验证响应——日志格式可能随Savon版本或配置变化,直接使用响应对象才是稳定的方案。
内容的提问来源于stack exchange,提问作者CountDubular
相关产品推荐
相关产品推荐

