离线运行 Rspec 时如何处理在线依赖关系?

发布于 2024-10-10 03:30:14 字数 162 浏览 9 评论 0原文

我想在连接到网络和未连接网络时运行 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

倾听心声的旋律 2024-10-17 03:30:14

通常在这种情况下,您会模拟连接应用程序外部的代码部分。这允许您根据您所连接的服务/系统的预期结果进行测试。运行测试也更快。

这里有一个关于使用 rspec 进行模拟的简短教程,但我相信您自己可以找到很多。

如果您通过 ActionMailer 发送电子邮件,则可以使用其他方法来测试电子邮件是否已发送。 rails 测试指南中有一节介绍了这一点。

编辑(回应评论):
您可以在 TestHelper 中放置一个方法,以便仅在在线时运行测试。比如:

def when_online
  if test_remote_connectivity
    yield
  else
    puts "Skipping test offline."
  end
end

那么你可以这样称呼它:

def test_facebook
  when_online do
    .....
  end
end

不确定我完全提倡它,但它可能会做你想要的!

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:

def when_online
  if test_remote_connectivity
    yield
  else
    puts "Skipping test offline."
  end
end

Then you can call it like:

def test_facebook
  when_online do
    .....
  end
end

Not sure I entirely advocate it but it might do what you want!

神经大条 2024-10-17 03:30:14

您可以在不想连接到远程资源的测试/规范中使用 webmock

You could use webmock inside the tests/specs you don't want connecting to the remote resource.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文