Rails – 如何为存根/伪造的http或ajax响应存根特定的响应时间

我想测试一个function,当我的应用程序在Rails UJS / ajax超时时发送usera自定义消息。

超时Rails UJS请求的代码本身就在应用程序上:

$.rails.ajax = function(options) { if (!options.timeout) { options.timeout = 10000; } return $.ajax(options); }; 

当观察chrome dev工具在我的本地开发模式下超时时发生的事情时,我注意到代码状态奇怪地是200但是当它“超时”时,我的消息确实显示给用户。

 on('ajax:error',function(event,xhr, status, error){ // display message in modal for users if(status == "timeout") { console.log( ' ajax request timed out'); var msg; msg = Messenger().post({ hideAfter: 8, message: "Too long, the app timed out" }); } } }); 

以下是我目前的测试(使用膨化法案gem )。 我设法为我的ajax请求存根http响应,但我不知道如何告诉rspec“等待”和超时,如需要11秒,仍然没有发送任何响应xhr调用:)(xhr max timeout设置为比10秒<11秒高10 000毫秒,它应该在rspec测试中超时)

 it " displays correct modal message appears correctly when xhr call timeout" do visit deal_page_path(deal) proxy.stub("http://127.0.0.1:59533/deals/dealname/ajaxrequest").and_return(:code => 200) first('a.button').click wait_for_ajax within('ul.messenger') do expect(page).to have_content('Too long, the app timed out') end end 

如果你真的希望它只是等待超时我相信你可以使用proc版本的and_return并且只要你想要请求就睡觉

 proxy.stub("http://127.0.0.1:59533/deals/dealname/ajaxrequest").and_return( Proc.new { |params, headers, body| sleep 11 {code: 200} } ) 

另外 – 而不是wait_for_ajax只传递你期望元素出现在within调用中的时间

 within('ul.messenger', wait: 11) do ...