Rails System Test: how to set default_host_url
Asked Answered
O

4

5
  • Rails: 5.2.1
  • Out of the box test setup
  • Running with chrome as driver (both normal and headless)

I am trying to run a System test where I access a external service, then get redirected back to my own application.

In this system test, how do I get access to the full url of the running test? I cannot find the current localhost port, therefore cannot send the correct redirect url to the external service.

Obey answered 19/8, 2018 at 12:34 Comment(0)
O
5

After some more searching the internets, I found an answer.

Based on this post, I added

def setup
    Rails.application.routes.default_url_options[:host] = Capybara.current_session.server.host
    Rails.application.routes.default_url_options[:port] = Capybara.current_session.server.port
end

to my application_system_test_case.rb.

This allows all _url methods to work in the system tests.

Obey answered 19/8, 2018 at 13:10 Comment(2)
I would put that in the shared test helper, not in just one test file. Otherwise, you'll be repeating it in every single system test.Higgledypiggledy
@TomLord I put it in the application_system_test_case.rb, so it is set for every system test.Obey
D
3

Rails 6. The only thing that worked for me:

# inside a subclass of ActionDispatch::IntegrationTest or ActionDispatch::SystemTestCase
setup do
  self.default_url_options = {...}
end
Dianadiandra answered 15/1, 2020 at 20:7 Comment(0)
H
1

In Rails 7.1.0, none of the answers above would work, but this did:

module ActionDispatch
  class IntegrationTest

    def setup
      host! 'localhost:3000'
    end
  end
end
Hoiden answered 28/3 at 23:9 Comment(0)
M
0

Update for Rails 6.1.6:

The default host seems to have been 127.0.0.1. To get it to match the server host and port in my development environment, in application_system_test_case.rb I used the following:

class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
  def setup 
    Capybara.server_host = "localhost" # or whatever you use in dev
    Capybara.server_port = 3000 # ditto
  end

  ...
Monarski answered 3/11, 2023 at 2:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.