如何在Rails开发环境中测试500.html页面?

49

我想在Rails应用的开发环境下测试500错误页面。

我已经在config/environments/development.rb中尝试过了:

config.action_controller.consider_all_requests_local = false

但是这似乎没有任何作用。


1
将您的环境更改为生产环境有帮助吗? - Nuby
我个人认为,最好在生产环境下测试错误页面。如果你总是在开发中禁用Rails内置的错误页面,可能会使查看有价值的调试信息更加困难。 - Nick McCurdy
8个回答

85

目前我找到的唯一方法是在development.rb中设置:

config.consider_all_requests_local = false

然后重新启动服务器。

接着使用我的本地IP地址访问URL: http://192.168.1.135:3000/blah

其他提到的设置似乎没有任何效果。


4
也适用于Rails 4。顺便说一句,对我来说,无论是使用127.0.0.1:3000/page_which_does_not_exist还是localhost:3000/page_which_does_not_exist都有效。 - Ben
对我来说不起作用。我得到的是没有路由匹配而不是内部服务器错误。 - oky_sabeni
6
在将 config.consider_all_requests_local 设为 false 后,别忘了重启服务器。 - Ross

30

在我的Rails 3应用程序中,没有任何一个提出的解决方案起作用。对我来说,一个快速而简单的解决办法就是直接访问错误页面以查看渲染的HTML。例如,

http://0.0.0.0:3000/404.html

http://0.0.0.0:3000/500.html

它对我不起作用。我得到了500错误页面,但我看到它被Rails服务器或开发日志记录下来。 - oky_sabeni

24

2
这是最短且最好的答案,适用于只想为这些页面测试设计的人。 - Joseph Rex

13

你可以采用以下两种方式:

  1. 使用与localhost或127.0.0.1不同的地址访问应用程序。Rails默认认为这些地址是本地请求。
  2. application_controller.rb中覆盖local_request?方法,例如:
def local_request?
  false
end
第二个选项将停止 Rails 将来自本地主机和 127.0.0.1 的请求视为本地请求,这与 consider_all_requests_local = false 结合使用应该显示您的 500.html 页面。

23
对于那些通过谷歌查找并使用Rails 3的人,请看下一个答案。 - corbin

9
除了设置: config.consider_all_requests_local = false 我还需要设置: config.action_dispatch.show_exceptions = true

请注意,此设置应在服务器启动之前进行,并且之后不会产生影响(可能不适用于需要同时使用两种行为的自动化测试)。 - Vasfed

4
您应该将以下行添加到application_controller中:
unless  ActionController::Base.consider_all_requests_local
    rescue_from Exception, :with => :render_500
    if  ActiveRecord::RecordNotFound
      rescue_from Exception, :with => :render_404
    end
    rescue_from ActionController::RoutingError, :with => :render_404
    rescue_from ActionController::UnknownController, :with => :render_404
    rescue_from ActionController::UnknownAction, :with => :render_404
end

接着,尝试使用以下设置运行。

config.action_controller.consider_all_requests_local = falseconfig/environments/development.rb: 中:

这将起作用。请不要忘记在 application_controller.rb 中编写函数来为每个错误消息呈现布局。


你也可以在控制器的顶部使用rescue_from指令,就像http://guides.rubyonrails.org/action_controller_overview.html#the-default-500-and-404-templates中所述。 - dooleyo
ActionController::UnknownAction 已经不存在了。 - webdevguy

0

我认为需要调整的正确设置是这样的:

config.action_view.debug_rjs = false

为什么它仍然被标记为rjs并不完全清楚。


这对我也没有任何影响。 - u2622

0

如果您只是想强制出现500错误来查看其外观,您可以将以下代码添加到视图中:

Haml示例:

= render :partial => "broken", :status => 500

1
为了帮助 OP 解决当前的问题,可以在回答中添加一些解释说明。 - ρяσѕρєя K

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接