Rails: Wrong hostname for url helpers in rspec

2019-04-07 13:36发布

问题:

Url helpers (e.g root_url) returns a different hostname in the app controllers vs rspec examples. I have successfully been able to set the domain for url helpers in my rails app like this:

class ApplicationController < ActionController::Base
  def default_url_options
    {host: "foo.com", only_path: false}
  end
end

For example, root_url outputs "http://foo.com/" within the application but "http://example.com" in my request specs. What is the recommended way to apply those url options globally in rails 3.2 so that they affect my specs? The url options do not need to be dynamic.

回答1:

In Feature specs, host! has been deprecated. Add these to your rspec_helper.rb:

# Configure Capybara expected host
Capybara.app_host = 'http://lvh.me:3000'

# Configure actual routes host during test
before(:each) do
  if respond_to?(:default_url_options)
    default_url_options[:host] = 'http://lvh.me:3000'
  end
end


回答2:

Just to add to Dan's answer it would look something like this in spec_helper.rb

RSpec.configure do |config|
  # other config options
  config.before(:each) do
    host! "localhost:3000"
  end
end


回答3:

You can set the host in a before block in your test in rspec:

    before :each do
      host! 'hostgoeshere.com'
    end

If you want to set it globally you could put something your spec_helper.rb file.



回答4:

I tried many variations of @request.host, host!, and post path, args, {'SERVER_NAME' => my_secret_domain} without success, both as controller tests and feature tests. Very aggravating, as so many others reported success with those approaches.

The solution for me was:

request.headers["SERVER_NAME"] = my_secret_domain
post path, args

I'm running ruby 2.1.5p273, rspec 3.1.7 and Rails 4.2.0