6

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.

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.

Any ideas?

Community
  • 1
  • 1
MakSaraksh
  • 61
  • 1
  • 5

1 Answers1

2

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:

In 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)

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

browser.goto "http://localhost:#{HTTP_PORT}/"
Mike Aski
  • 9,180
  • 4
  • 46
  • 63