ruby 地理编码rake任务与测试

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 地理编码rake任务与测试相关的知识,希望对你有一定的参考价值。

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

以上是关于ruby 地理编码rake任务与测试的主要内容,如果未能解决你的问题,请参考以下文章

如何在'rake test'中关闭警告'ruby -w'?

在“rake test”之后执行 rake 任务

rake db rake 任务不工作 Ruby 2.4.0 & Rails 5.0.1

如何在 Ruby 脚本中运行 Rake 任务?

ruby 修复了rake资产:预编译任务

ruby Rails中自定义rake任务