Ruby-on-rails 如何为 Rails 控制器添加延迟以进行测试?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7098732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:47:44  来源:igfitidea点击:

How to add a delay to Rails controller for testing?

ruby-on-railsrubyajaxruby-on-rails-3testing

提问by RSG

I'm testing the front end of a web application and want to test how some of the transitions appear with various delays in between AJAX requests. Is there any way I can add a sleep(1500)to my controller to delay the response?

我正在测试 Web 应用程序的前端,并想测试一些转换如何在 AJAX 请求之间出现各种延迟。有什么方法可以sleep(1500)向我的控制器添加一个来延迟响应?

回答by RSG

Controller like so:

像这样的控制器:

def catalog
  #Makes the request pause 1.5 seconds
  sleep 1.5

  ...
end

Even better: only add the sleep for the dev environment.

更好的是:只为开发环境添加睡眠。

回答by jmarceli

Elaborating on accepted answer. If you have some base controller like the default ApplicationControllerwhich is extended by any other controller you may define the following filter:

详细说明已接受的答案。如果您有一些基本控制器,例如ApplicationController由任何其他控制器扩展的默认控制器,您可以定义以下过滤器:

class ApplicationController < ActionController::Base

  # adds 1s delay only if in development env
  before_filter if: "Rails.env.development?" do
    sleep 1
  end
end

Where: 1is number of seconds to wait before returning any response, see sleepdocs

其中: 1是在返回任何响应之前等待的秒数,请参阅sleep文档

This filter will be triggered only ifyour application is in developmentenvironment and it will add desired delay to every requestprocessed by your application.

仅当您的应用程序处于开发环境中时才会触发此过滤器,它将为应用程序处理的每个请求添加所需的延迟。