Topic: Mocking request.remote_ip for testing.

Hello,

    I'm writing test for some geo-location methods which are all very IP dependent.   

Is there a good way to mock a request.remote_ip?

Thanks for any help,

Clem C

Re: Mocking request.remote_ip for testing.

Guess you can just re-define it on the @request variable in setup.

require File.dirname(__FILE__) + '/../test_helper'
require 'foo_controller'

# Re-raise errors caught by the controller.
class FooController; def rescue_action(e) raise e end; end

class FooControllerTest < Test::Unit::TestCase
  def setup
    @controller = FooController.new
    @request    = ActionController::TestRequest.new
    @response   = ActionController::TestResponse.new
   
    @request.instance_eval do
      def remote_ip
        "666.13.37.911"
      end
    end
  end
end

Re: Mocking request.remote_ip for testing.

Or use a mocking framework like mocha:

@request.stubs(:remote_ip).returns("1.2.3.4")

Railscasts - Free Ruby on Rails Screencasts

Re: Mocking request.remote_ip for testing.

Thanks - that was exactly what i was looking for!