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.
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
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
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.
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