Testing geolocation with capybara + selenium + firefox

Just built this little snippet in a hacknight, it simulates a geolcation via capybara, so you can test if you geo-magic actually works 🙂

View

<p>Finding your location... <span id="status">checking...</span></p>
<script>
  jQuery(function () {
    var timeout = (document.location.href.indexOf('test_location') >= 0 ? 100 : 0);

    setTimeout(function(){
      navigator.geolocation.getCurrentPosition(function(){
        jQuery('#status').html("found you!");
      });
    }, timeout)
  });
</script>

Capybara test via selenium in rspec

  def simulate_location(lat, lng)
    page.driver.browser.execute_script <<-JS
      window.navigator.geolocation.getCurrentPosition = function(success){
        var position = {"coords" : { "latitude": "#{lat}", "longitude": "#{lng}" }};
        success(position);
      }
    JS
  end

  it "can use location", :js => true do
    visit '/?test_location=true'
    simulate_location 20, 20
    sleep 0.2
    page.should have_content "found you!"
  end

4 thoughts on “Testing geolocation with capybara + selenium + firefox

  1. I have something very similar to what you lay out in this post, only I don’t have the `setTimeout` part. My test passes some of the time, and fails some of the time, and I suspect that it has to do with the timeout thing you do… can explain why you do that? Do you need to give the page time to load before replacing the `getCurrentPosition` method?

  2. Oh actually I just realized I was missing the `sleep 0.2` after the stubbing of the `getCurrentPosition`. But I’d still like to understand the timeout thing 🙂

Leave a comment