rspec 测试中的 Rails 应用程序端口号 [英] Rails application's port number in a rspec test

查看:47
本文介绍了rspec 测试中的 Rails 应用程序端口号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 rspec 结合 faraday 和 faraday_middleware 来测试 rails 应用程序的 json 响应.要使用法拉第,需要应用程序 URL.在测试中,我想使用 localhost + 端口号.

I would like to test the json responses of a rails application using rspec in combination with faraday and faraday_middleware. To use faraday one needs the application URL. In the tests I would like to use localhost + a port number.

问题是,如何在rspec测试环境中获取或设置当前应用程序实例的端口号?

The question is, how can I get or set the port number of the current application instance in a rspec test environment?

有类似的问题,但没有令人满意的答案这里此处.

There are a similar questions but no satisfying answers here and here.

有什么想法吗?

推荐答案

我有同样的需求 (Watir+RSpec),但问题是:在测试期间默认没有运行 Rack 堆栈...

I had the same need (Watir+RSpec), but the problem is: there is no Rack stack running by default during tests...

我找到了这个解决方案:

I found this solution:

spec_helper.rb 中:

HTTP_PORT = 4000

test_instance_pid = fork do
  exec 'unicorn_rails -E test -p %d' % HTTP_PORT
end

at_exit do
  Process.kill "INT", test_instance_pid
  Process.wait
end

为所有规范测试启动一次测试堆栈,并在最后终止它.(在这个示例中,我使用的是独角兽,但我们可以想象使用任何其他服务器)

Which start the test stack once for all spec tests, and kill it at the end. (In this sample, I am using unicorn, but we can imagine using any other server)

在规范中,我重用了 HTTP_PORT 常量来构建 URL:

In the spec, I reuse the HTTP_PORT constant to build URL:

browser.goto "http://localhost:#{HTTP_PORT}/"

这篇关于rspec 测试中的 Rails 应用程序端口号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆