0

I have a site hosted on Heroku. For SEO purposes I am trying to use strictly my bare domain (https://example.com/).

I found this medium article suggesting to insert this code into routes.rb

match '(*any)', to: redirect(subdomain: ''), via: :all, constraints: {subdomain: 'www'}

Seems like a easy and efficient way to handle redirecting to bare domain in Rails.

However, now all my tests are failing with the message:

Expected response to be a redirect to <http://www.example.com/> but was a redirect to <http://example.com/>.

And

Expected response to be a <2XX: success>, but was a <301: Moved Permanently> redirect to <http://example.com/>

I can somewhat fix this by replacing assert_response :success with assert_response :redirect in my test logic for page loads.

My question is, would changing all my tests to assert_response :response be best practice? Or is there an easier way to configure bare domain redirects in Rails 6 that does not interfere with test logic?

Example of test:

  test "should get example page" do
    get example_path
    assert_response :success
  end

Routes.rb

 root to: "site#index"

 get "example", to: "site#example
Owen Roth
  • 41
  • 4
  • It seems your test requests include the `www.` subdomain, triggering the redirect. Can you include more about these tests? (e.g. what testing framework, an example of the test that's failing, what route you're requesting, etc). You should be able to change your tests to not use the `www.` subdomain. – melcher Sep 01 '21 at 17:59
  • can you add the relevant `routes` definition for the example path? – melcher Sep 01 '21 at 18:43
  • Added the `routes` definition above – Owen Roth Sep 01 '21 at 18:49
  • I'm not sure why the get request is hitting your redirect route w/ the `www` constraint. Using the `_path` like you're doing shouldn't know to use a subdomain constraint, see: https://stackoverflow.com/questions/9329669/testing-routes-with-subdomain-constraints-using-rspec – melcher Sep 01 '21 at 18:49
  • My guess would be there's code that is setting the host manually to `www.example.com` in your test setup, something like https://stackoverflow.com/questions/2556627/rails-rspec-set-subdomain/30413528#30413528 – melcher Sep 01 '21 at 18:50

1 Answers1

0

The issue is that the default URL used for rails testing happens to be www.example.com, which is hitting your route.

See more details here How do I change the default "www.example.com" domain for testing in rails?

This hits your redirect route. Change the default host to remove the www and it should fix the problem, e.g.

controller.request.host = "example.com"
melcher
  • 1,543
  • 9
  • 15