require 'rails_helper'
describe "geocoding:existing" do
include_context "rake"
describe "#initialize" do
it { expect(subject.prerequisites).to include('environment') }
it "should return objects with latitude.nil? or longitude.nil?" do
member = FactoryGirl.build(:member)
member.save(:validate => false)
expect(member.longitude).to be_nil
expect(member.latitude).to be_nil
end
end
describe "#execution" do
let(:members) { [] }
let(:count) { rand(5..10) }
context "when the CLASS=model is not set" do
it "should raise an error" do
expect{ subject.invoke }.to raise_error
end
end
context "when the CLASS=model is set" do
it "should process the task" do
ENV['CLASS']='Member'
expect(subject.invoke).to be_truthy
ENV['CLASS']='' #resetting the enviornmental variables
end
context "when geocoding is successful" do
before :each do
mock_geocoding!
count.times { members << FactoryGirl.create(:member) }
end
it "should geocode the object" do
ENV['CLASS']='Member'
expect(subject.invoke).to be_truthy
members.each do |member|
expect(member.geocoded?).to be_truthy
end
ENV['CLASS']='' #resetting the enviornmental variables
end
end
context "when geocoding is not successful" do
context "when it raises an error" do
end
end
end
end
end
namespace :geocoding do
desc "Geocode all existing addresses without coordinates (longitude.nil? || latitude.nil?)."
task :existing => :environment do
class_name = ENV['CLASS'] || ENV['class']
sleep_timer = ENV['SLEEP'] || '0.25'
batch = ENV['BATCH'] ||= '50'
raise "Please specify a CLASS (model)" unless class_name
klass = class_from_string(class_name)
batch = batch.to_i unless batch.nil?
klass.not_geocoded.find_each(:batch_size => batch) do |obj|
obj.geocode; obj.save
end
sleep(sleep_timer.to_f) unless sleep_timer.nil?
end
end
end
#
#USAGE: rake geocoding:existing CLASS=model SLEEP=n (default is 0.25) BATCH=n (default is 50)
#get a class object from the string given in the shell environment.
#Similar to ActiveSupport's +constantize+ method.
#http://apidock.com/rails/String/constantize
#
def class_from_string(class_name)
parts = class_name.split("::")
constant = Object
parts.each do |part|
constant = constant.const_get(part)
end
constant
end