2019-04-29 20:27:42 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2022-07-27 22:27:38 -04:00
|
|
|
RSpec.describe Positionable do
|
2013-10-18 03:09:30 -04:00
|
|
|
def positions
|
|
|
|
TestItem.order("position asc, id asc").pluck(:id)
|
|
|
|
end
|
|
|
|
|
2022-07-27 12:14:14 -04:00
|
|
|
describe "move_to" do
|
2013-10-18 03:09:30 -04:00
|
|
|
before do
|
|
|
|
class TestItem < ActiveRecord::Base
|
2014-04-19 00:00:40 -04:00
|
|
|
include Positionable
|
2013-10-18 03:09:30 -04:00
|
|
|
end
|
|
|
|
|
2018-06-19 02:13:14 -04:00
|
|
|
DB.exec("create temporary table test_items(id int primary key, position int)")
|
2013-10-18 03:09:30 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
after do
|
2018-06-19 02:13:14 -04:00
|
|
|
DB.exec("drop table test_items")
|
2013-10-18 03:09:30 -04:00
|
|
|
|
2019-04-30 02:58:18 -04:00
|
|
|
# this weakref in the descendant tracker should clean up the two tests
|
|
|
|
# if this becomes an issue we can revisit (watch out for erratic tests)
|
|
|
|
Object.send(:remove_const, :TestItem)
|
2013-10-18 03:09:30 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
it "can position stuff correctly" do
|
2018-06-19 02:13:14 -04:00
|
|
|
5.times { |i| DB.exec("insert into test_items(id,position) values(#{i}, #{i})") }
|
2013-10-18 03:09:30 -04:00
|
|
|
|
2015-01-09 11:34:37 -05:00
|
|
|
expect(positions).to eq([0, 1, 2, 3, 4])
|
2013-10-18 03:09:30 -04:00
|
|
|
TestItem.find(3).move_to(0)
|
2015-01-09 11:34:37 -05:00
|
|
|
expect(positions).to eq([3, 0, 1, 2, 4])
|
|
|
|
expect(TestItem.pluck(:position).sort).to eq([0, 1, 2, 3, 4])
|
2013-10-18 03:09:30 -04:00
|
|
|
|
2013-10-21 01:14:09 -04:00
|
|
|
TestItem.find(3).move_to(1)
|
2015-01-09 11:34:37 -05:00
|
|
|
expect(positions).to eq([0, 3, 1, 2, 4])
|
2013-10-18 03:09:30 -04:00
|
|
|
|
2013-12-16 15:13:43 -05:00
|
|
|
# this is somewhat odd, but when there is no such position, not much we can do
|
2013-10-18 03:09:30 -04:00
|
|
|
TestItem.find(1).move_to(5)
|
2015-01-09 11:34:37 -05:00
|
|
|
expect(positions).to eq([0, 3, 2, 4, 1])
|
2013-10-18 03:09:30 -04:00
|
|
|
|
2015-01-09 11:34:37 -05:00
|
|
|
expect(TestItem.pluck(:position).sort).to eq([0, 1, 2, 3, 4])
|
2013-10-18 03:09:30 -04:00
|
|
|
|
|
|
|
item = TestItem.new
|
|
|
|
item.id = 7
|
|
|
|
item.save
|
2015-01-09 11:34:37 -05:00
|
|
|
expect(item.position).to eq(5)
|
2013-10-18 03:09:30 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|