2015-10-11 17:41:23 +08:00
|
|
|
require "rails_helper"
|
2013-10-18 15:09:30 +08:00
|
|
|
|
2014-04-19 12:00:40 +08:00
|
|
|
describe Positionable do
|
2013-10-18 15:09:30 +08:00
|
|
|
|
|
|
|
def positions
|
|
|
|
TestItem.order('position asc, id asc').pluck(:id)
|
|
|
|
end
|
|
|
|
|
|
|
|
context "move_to" do
|
|
|
|
before do
|
|
|
|
class TestItem < ActiveRecord::Base
|
2014-04-19 12:00:40 +08:00
|
|
|
include Positionable
|
2013-10-18 15:09:30 +08:00
|
|
|
end
|
|
|
|
|
2018-06-19 14:13:14 +08:00
|
|
|
DB.exec("create temporary table test_items(id int primary key, position int)")
|
2013-10-18 15:09:30 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
after do
|
2018-06-19 14:13:14 +08:00
|
|
|
DB.exec("drop table test_items")
|
2013-10-18 15:09:30 +08:00
|
|
|
|
|
|
|
# import is making my life hard, we need to nuke this out of orbit
|
|
|
|
des = ActiveSupport::DescendantsTracker.class_variable_get :@@direct_descendants
|
|
|
|
des[ActiveRecord::Base].delete(TestItem)
|
|
|
|
end
|
|
|
|
|
|
|
|
it "can position stuff correctly" do
|
|
|
|
5.times do |i|
|
2018-06-19 14:13:14 +08:00
|
|
|
DB.exec("insert into test_items(id,position) values(#{i}, #{i})")
|
2013-10-18 15:09:30 +08:00
|
|
|
end
|
|
|
|
|
2017-07-28 09:20:09 +08:00
|
|
|
expect(positions).to eq([0, 1, 2, 3, 4])
|
2013-10-18 15:09:30 +08:00
|
|
|
TestItem.find(3).move_to(0)
|
2017-07-28 09:20:09 +08: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 15:09:30 +08:00
|
|
|
|
2013-10-21 13:14:09 +08:00
|
|
|
TestItem.find(3).move_to(1)
|
2017-07-28 09:20:09 +08:00
|
|
|
expect(positions).to eq([0, 3, 1, 2, 4])
|
2013-10-18 15:09:30 +08:00
|
|
|
|
2013-12-17 04:13:43 +08:00
|
|
|
# this is somewhat odd, but when there is no such position, not much we can do
|
2013-10-18 15:09:30 +08:00
|
|
|
TestItem.find(1).move_to(5)
|
2017-07-28 09:20:09 +08:00
|
|
|
expect(positions).to eq([0, 3, 2, 4, 1])
|
2013-10-18 15:09:30 +08:00
|
|
|
|
2017-07-28 09:20:09 +08:00
|
|
|
expect(TestItem.pluck(:position).sort).to eq([0, 1, 2, 3, 4])
|
2013-10-18 15:09:30 +08:00
|
|
|
|
|
|
|
item = TestItem.new
|
|
|
|
item.id = 7
|
|
|
|
item.save
|
2015-01-10 00:34:37 +08:00
|
|
|
expect(item.position).to eq(5)
|
2013-10-18 15:09:30 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|