Alex Rivera | Logout

Setting default_url_options in test environment doesn't seem to work

Asked 2012-10-22T03:06:30.907
15

I've put the following code into my config/environments/test.rb file:

config.action_mailer.default_url_options = { :host => "localhost:3000" }

however when I run my tests, all routes use http://test.host. I'm trying to work with an API that won't accept http://test.host as a valid callback URI, so I need to change this to properly receive the API response. Any idea why this isn't working? (I'm using RSpec, Guard, and Spork in my testing suite).

EDIT: Possibly relevant - this is being done inside of a controller spec.

EDIT2: It seems that it changes after a request is made via get, post, etc. Running the following code within the test:

Rails.logger.debug users_url
get 'http://google.com'
Rails.logger.debug users_url

would produce the following output:

http://localhost:3000/users
...get request related response here
http://google.com/users
Edit
Report

1 Answer

0

From my experience, url_options will not be passed into tests without a bit of hacking.

See e.g.

I've frequently encountered this problem when trying to set the locale in tests. I've never used action mailer, though, so there may be a simpler way to do it.

The solution I've found for setting the default locale in url_options is just to patch actiondispatch and force it to use whatever locale I want it to. You could adapt this to your case this way:

class ActionDispatch::Routing::RouteSet
  def url_for_with_default_url_options(options)
    url_for_without_default_url_options(options.merge(:host => "localhost:3000" ))
  end

  alias_method_chain :url_for, :default_url_options
end

I put that code in a file in spec/support so it is used in rspec tests and I also require it from my env.rb file so I can use it in cucumber tests as well.

Keep in mind that this will patch it everywhere, in both test code and in actual code running under tests, and it will override any other settings for the :host key that you try to pass in (since the patch merges the fix on top of the options passed into url_for). In your case I believe that shouldn't be a problem.

Monkey patching is not a very elegant solution, though, and I used this after everything else failed. You might find a simpler solution specific to action mailer.

answered 2012-10-22T04:15:23.480

Your Answer