离线运行 Rspec 时如何处理在线依赖关系?
我想在连接到网络和未连接网络时运行 RSpec 来测试我的代码。
不幸的是,应用程序中有一些测试依赖于实时连接 - 电子邮件发送、Facebook 集成等。
是否有创建在线/离线测试环境的最佳实践方法,或者这是不好的做法?从我在网上能找到的关于这方面的信息很少来看,我猜是后者。
I would like to run RSpec to test my code both when I'm connected to the web and when I'm not.
Unfortunately there are some tests in the application which are dependent on having a live connection - email sending, Facebook integration etc.
Is there a best-practice way to create an online/offline testing environment or is this bad practice? Judging by how little I can find about this on the web I'm guessing the latter.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通常在这种情况下,您会模拟连接应用程序外部的代码部分。这允许您根据您所连接的服务/系统的预期结果进行测试。运行测试也更快。
这里有一个关于使用 rspec 进行模拟的简短教程,但我相信您自己可以找到很多。
如果您通过 ActionMailer 发送电子邮件,则可以使用其他方法来测试电子邮件是否已发送。 rails 测试指南中有一节介绍了这一点。
编辑(回应评论):
您可以在
TestHelper
中放置一个方法,以便仅在在线时运行测试。比如:那么你可以这样称呼它:
不确定我完全提倡它,但它可能会做你想要的!
Normally in situations like that you would mock the parts of the code that connect outside your application. This allows you to test against the expected results from the service/system you are connecting to. It's also quicker to run tests.
There's a brief tutorial on mocking with rspec here but I'm sure you can find plenty yourself.
For testing that emails get sent there are other approaches if you are sending through ActionMailer. There's a section on that in the rails testing guide.
EDIT (in response to comment):
You could put a method in
TestHelper
to only run tests when you are online. Something like:Then you can call it like:
Not sure I entirely advocate it but it might do what you want!
您可以在不想连接到远程资源的测试/规范中使用 webmock 。
You could use webmock inside the tests/specs you don't want connecting to the remote resource.