3

尝试模拟Faraday::Response对象时,我尝试过:

mock(Faraday::Response, :env => {:body => "...some xml..."})

...但是当我调用时这会失败response.body.xpath(...),因为主体是一个字符串,并且它需要一个 NodeSet。

有没有一种简单的方法可以将任意 XML 字符串转换为 NodeSet?我已经阅读了Nokogiri::XML::NodeSet文档,但它要么不存在,要么我错过了它。

这是我的实际存根+模拟:

@conn.stub!(:get).and_return(mock Faraday::Response,
      :env => {:status=>207},
      :body => '<scheduled-calendar xmlns="[removed]" xmlns:xsi="[removed]" id="95ec6d99-2c4a-4e25-99a1-2e988c0dbce6" assignment-id="uuid_for_test" xsi:schemaLocation="[removed]" debug="true">
                <scheduled-study-segment id="4e5b24e3-b50a-45e2-aec1-cb6c839a20f1" start-date="2012-01-06" start-day="1" study-segment-id="524910e9-634a-4791-a0b2-90f506a86474">
                <scheduled-activity id="1caa08b2-acb0-4c93-8c76-6460f0e9ee09" ideal-date="2012-01-06" details="Screening survey" repetition-number="0" planned-activity-id="1fc520dd-5b6f-4125-b83c-2f8801ea3065">
                <current-scheduled-activity-state reason="Initialized from template" date="2012-01-06" state="conditional"/>
                </scheduled-activity>
                </scheduled-study-segment>
                </scheduled-calendar>'
    )

这是调用xpath

response.body.xpath('//psc:scheduled-activity', Psc.xml_namespace).collect{|activity| activity.attributes["id"].value}

这是测试失败:

NoMethodError in 'PscV1 should allow you to get a list of scheduled activity ids for a given involvement'
undefined method `xpath' for #<String:0x10dad1818>
4

1 回答 1

1

因此,基本上答案是法拉第没有将我的身体视为 XML,因此,只是将响应作为字符串传回,而不是Nokogiri::XML::Document

通过做...

xml = Nokogiri::XML('<scheduled-calendar xmlns="[removed]" xmlns:xsi="[removed]" id="95ec6d99-2c4a-4e25-99a1-2e988c0dbce6" assignment-id="uuid_for_test" xsi:schemaLocation="[removed]" debug="true">
            <scheduled-study-segment id="4e5b24e3-b50a-45e2-aec1-cb6c839a20f1" start-date="2012-01-06" start-day="1" study-segment-id="524910e9-634a-4791-a0b2-90f506a86474">
            <scheduled-activity id="1caa08b2-acb0-4c93-8c76-6460f0e9ee09" ideal-date="2012-01-06" details="Screening survey" repetition-number="0" planned-activity-id="1fc520dd-5b6f-4125-b83c-2f8801ea3065">
            <current-scheduled-activity-state reason="Initialized from template" date="2012-01-06" state="conditional"/>
            </scheduled-activity>
            </scheduled-study-segment>
            </scheduled-calendar>')

xml然后将该变量作为正文传递...

@conn.stub!(:get).and_return(mock Faraday::Response,
  :env => {:status=>207},
  :body => xml
)

...问题已解决。

于 2012-01-09T18:05:12.167 回答