Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails application's port number in a rspec test

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?

like image 515
MakSaraksh Avatar asked Aug 14 '11 15:08

MakSaraksh


1 Answers

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}/"
like image 51
Mike Aski Avatar answered Oct 20 '22 17:10

Mike Aski