samedi 28 novembre 2015

How to mock Geocoder with Mocha in Rails

I'm wanting to mock HTTP calls made by Geocoder. I found this post - How can I optionally mock geocoder?

Here is my model

class Listing < ActiveRecord::Base
  geocoded_by :address
  before_save :geocode, :if => :address_changed?
end

There were two recommendations: VCR (for HTTP requests only?), and Mocha.

I like the looks of Mocha as I can use this for other objects (e.g. models), not just HTTP requests. However, the poster wasn't familiar with Geocoder and didn't know what methods of it to mock, neither do I - still a little new to Rails. Not really sure how/where to trace method calls.

My test looks like this:

test "should create listing" do
  sign_in @current_user

  assert_difference('Listing.count') do
    post :create, listing: valid_params
  end
  listing = Listing.last

  # confirm lat/lng are set
  assert_not_nil listing.latitude
  assert_not_nil listing.longitude

  assert_redirected_to listing_path(assigns(:listing))
end

The test passes, but it can be a little slow to run as it is doing the HTTP request during the test. Would be good to just mock this part in Geocoder.

Alternatively I'll give VCR a go if Geocoder doesn't work with Mocha.

Aucun commentaire:

Enregistrer un commentaire