在 Ruby 生产中使用断言...是还是否?
所以,这就是交易。我目前在 Ruby on Rails 环境中工作,已经工作约 1 年了。在此之前,我在 C++/Java 领域工作了近十年。我(仍在)试图弄清楚 Ruby 的断言方式是什么。
我不担心技术细节。我知道 TestUnit 有可以在测试环境中使用的断言,并且我知道我可以将自己的断言方法添加到我的 Ruby 项目中,并在生产 Rails 中使用它们来锁定已知条件。问题是:Ruby 的方式是什么来确保代码中我知道应该/不应该发生的事情?
作为记录,我一直在测试中断言并在生产中提高。我仍然忍不住想念我的生产断言......
So, here's the deal. I'm currently working in a Ruby on Rails environment and have been for ~1 year now. Before that I was in C++/Java land for almost a decade. I'm (still) trying to figure out what the Ruby way is when it comes to asserts.
I'm not worried about the technical detail. I know TestUnit has asserts which can be used in the testing environment and I know I can add my own assert methods to my Ruby project and use them in production Rails to lock down known conditions. The question is: What is the Ruby way for ensuring something in code that I know should/not happen?
For the record, I've been asserting in tests and raising in production. I still can't help but miss my production asserts...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
断言确实不应该在生产代码中使用,原因有两个。
assert x
功能非常强大,因此很难阅读。使用 raise/if 组合可以增加可读性。assert 没有明确说明如果条件失败将会引发什么错误。同时,
如果条件成立则引发 ObscureButInformitiveError
让应用程序层进一步做一些相关的事情。例如向管理员发送电子邮件或写入特定日志。
Asserts really shouldn't be used in production code for two reasons.
assert x
is very functional, and as such hard to read. Using a raise/if combo adds readability.assert doesn't make it clear what error will be raised if the condition fails. While,
raise ObscureButInformitiveError if condition
lets the application layers further up do something relveant. Such as emailing an admin, or writing to a perticular log.
让错误发生,然后检查日志中是否出了问题,然后修复它。
Rails 会自动捕获所有未捕获的异常,它只会弄乱发生错误的单个请求。
Let the error happen, then check the logs for what went wrong, then fix it.
Rails catches all uncaught exceptions automatically, it will only mess up the single request the error happened in.
Ruby 中没有官方的非测试断言,但有 gem。
例如 Jim Weirich 的 Given 看起来很有希望。虽然它的主要重点是测试环境(rspec / minitest),但它还:
There's no official non-test assertions in Ruby, but there are gems.
For instance Jim Weirich's Given looks promising. Although its main focus is testing environments (rspec / minitest), but it also: