Rails 功能测试未捕获/获取异常
有一天,当运行我的应用程序的功能测试之一时,我在代码中遇到了一个错误,该错误导致了 RoutingError
。我的功能测试正在加载一个页面,并在该页面中创建一个指向没有有效路由的页面的链接。不过,异常的具体原因不是重点 - 问题是该异常没有传递回我的测试。我知道发生异常的唯一原因是我碰巧在 test.log
文件中注意到它。简而言之,测试通过了,但我认为这应该算作失败!
这让我很困惑。我尝试将测试代码放入 assert_nothing_raised
块中,但它仍然通过。
进一步挖掘,我开始意识到我的应用程序抛出的任何异常都会被静默记录,并且不会导致测试失败。这是Rails 中的故意行为还是听起来像是我设置错误?
编辑: 我认为问题可能是 Rails 捕获并处理异常(以便当从浏览器发送请求时它可以显示熟悉的堆栈跟踪页面)。我明白为什么这在开发
环境中很有用,但在测试
环境中肯定没有用......?
When running one of my app's functional tests the other day I hit a bug in my code that was causing a RoutingError
. My functional test was loading a page and in that page it was creating a link to a page that had no valid route to it. The specific cause of the exception is not the point though - the problem was that this exception was not passed back to my test. The only reason I know the exception occurred was because I happened to notice it in the test.log
file. In short the test passed but I think that should count as a fail!
This confused me. I tried putting my test code in an assert_nothing_raised
block but it still passed.
Digging further I came to realise that any exception thrown by my app was being silently logged and not causing tests to fail. Is this intentional behaviour in Rails or does it sound like I've got something set up wrong?
EDIT:
I think the problem might be that Rails catches and handles the exception (so that it can present the familiar stack-trace page when the request is sent from a browser). I can see why this is useful in the development
environment, but surely not in the test
environment...?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该在功能测试中显式检查每个操作的响应,尝试执行以下操作:
get :index
assert_response :成功后,
您应该始终对响应有某种形式的断言。当操作应该重定向时,您可以使用assert_redicted_to
You should be explicitly checking the response of each action in your functional tests, try doing something like this instead:
get :index
assert_response :success
you should always have some form of assertion for the response. When the action is supposed to redirect you use assert_redicted_to