Eric Yang
Eric Yang

Reputation: 1889

Rails 3.1 set host in test environment

I'm getting http://www.example.com whenever I use root_url in my tests.

It works fine in development, where I have this in config/environments/development.rb:

Rails.application.routes.default_url_options[:host]= 'localhost:3000'

Adding this doesn't work in config/environments/test.rb, though. What should I add to use localhost:3000 as the host in the test environment?

Upvotes: 4

Views: 2630

Answers (1)

Chris Salzberg
Chris Salzberg

Reputation: 27374

Testing code that depends on default_url_options causes all kinds of problems, see this thread and this issue for examples.

I've solved the problem by patching ActionDispatch::Routing::RouteSet in tests to force rails to include defaults for whatever options I want (in my case locale). See my answer in the github issue linked to above for details.

To override the host option using the same approach:

class ActionDispatch::Routing::RouteSet
  def url_for_with_host_fix(options)
    url_for_without_host_fix(options.merge(:host => 'localhost:3000'))
  end

  alias_method_chain :url_for, :host_fix
end

Put this in a file in support, should do the trick.

Upvotes: 5

Related Questions