Add some tests

This commit is contained in:
Eugene Burmakin 2025-01-24 15:58:44 +01:00
parent 6e9c981329
commit 01275d0d2e
6 changed files with 65 additions and 3 deletions

View file

@ -11,9 +11,9 @@ class Trip < ApplicationRecord
def create_path!
trip_path = Tracks::BuildPath.new(points.pluck(:latitude, :longitude)).call
distance = calculate_distance
update_columns(path: trip_path, distance: distance) # Avoids recursion with `after_save`
self.distance = calculate_distance
self.path = trip_path
end
def points

View file

@ -2,6 +2,9 @@
class CreatePathsForTrips < ActiveRecord::Migration[8.0]
def up
Trip.find_each do |trip|
Trips::CreatePathJob.perform_later(trip.id)
end
end
def down

View file

@ -7,6 +7,8 @@ FactoryBot.define do
started_at { DateTime.new(2024, 11, 27, 17, 16, 21) }
ended_at { DateTime.new(2024, 11, 29, 17, 16, 21) }
notes { FFaker::Lorem.sentence }
distance { 100 }
path { 'LINESTRING(1 1, 2 2, 3 3)' }
trait :with_points do
after(:build) do |trip|

View file

@ -1,5 +1,23 @@
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Trips::CreatePathJob, type: :job do
pending "add some examples to (or delete) #{__FILE__}"
let!(:trip) { create(:trip, :with_points) }
let(:points) { trip.points }
let(:trip_path) do
"LINESTRING (#{points.map do |point|
"#{point.longitude.to_f.round(5)} #{point.latitude.to_f.round(5)}"
end.join(', ')})"
end
before do
trip.update(path: nil, distance: nil)
end
it 'creates a path for a trip' do
described_class.perform_now(trip.id)
expect(trip.reload.path.to_s).to eq(trip_path)
end
end

View file

@ -21,6 +21,10 @@ RSpec.describe Trip, type: :model do
it 'sets the distance' do
expect(trip.distance).to eq(calculated_distance)
end
it 'sets the path' do
expect(trip.path).to be_present
end
end
describe '#countries' do

View file

@ -0,0 +1,35 @@
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Tracks::BuildPath do
describe '#call' do
let(:coordinates) do
[
[45.123456, -122.654321], # [lat, lng]
[45.234567, -122.765432],
[45.345678, -122.876543]
]
end
let(:service) { described_class.new(coordinates) }
let(:result) { service.call }
it 'returns an RGeo::Geographic::SphericalLineString' do
expect(result).to be_a(RGeo::Geographic::SphericalLineStringImpl)
end
it 'creates a line string with the correct number of points' do
expect(result.num_points).to eq(coordinates.length)
end
it 'correctly converts coordinates to points with rounded values' do
points = result.points
coordinates.each_with_index do |(lat, lng), index|
expect(points[index].x).to eq(lng.to_f.round(5))
expect(points[index].y).to eq(lat.to_f.round(5))
end
end
end
end