Search code examples
ruby-on-railstestingrspecgmaps4rails

How to stub Gmap4rails


I want to implement a rspec test for a ruby on rails project. Some of the classes uses gmaps4rails

factories.rb:

 FactoryGirl.define do
   factory :place do |s|
      sequence(:name) {|n| "test  place#{n}" }
   end
 end

factorytest_spec.rb (with require 'spec_helper')

it "Test" do
Place.any_instance.stub(:geocode).and_return("..")
  8.times do
    s = FactoryGirl.build(:shop_with_adress)
  end
end

Now this code sometimes goes through green, sometimes not.

 Failure/Error: s = FactoryGirl.build(:place)
 ActiveRecord::RecordInvalid:

this seems to boild down to a Gmaps4rails Adress invalid error (?) How should I stub gmaps4rails? I don't really get how to apply the hints from How to stub gmaps4rails geocode functions in rspec tests? exactly.. Maybe because I'm quite new to stubbing/rspec.


Solution

  • You could copy the stub on Gmaps4rails.geocode detailled here and adapt it to your needs if necessary.

    For customization, copy paste the result of:

    Gmaps4rails.geocode("your custom address")
    

    Which is an Array and copy it:

    Gmaps4rails.stub(:geocode) do |*args|
      your_custom_array
    end
    

    Obviously, I recommend, like in the gem, to create your own spec support module.