MakSaraksh
MakSaraksh

Reputation: 61

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?

Upvotes: 6

Views: 2569

Answers (1)

Mike Aski
Mike Aski

Reputation: 9236

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}/"

Upvotes: 2

Related Questions