I am working on some specs for my Rails app that involve re-ordering Models in the database.
Since the Model IDs are not known ahead of time, I don’t want to hard-code the “List of Model IDs should be [1,2,3]”, so I simply collect them in an array as I create them, e.g.
(1..3).each
ids << Model.create().id
Model.find(:all, order: position).should == ids
Anyway, I want to test my reorder logic that takes a list of ordered IDs:
Model.reorder( [3,1,2] ) # will change position in db
to keep things DRY I just do:
reordered_ids = [ids[3], ids[1], ids[2]]
Model.reorder( reordered_ids )
Model.find(...).should == reordered_ids
I was curious if there’s a more elegant way to doing
reordered_ids = [ids[3], ids[1], ids[2]]
This works but doesn’t seem better:
[3,1,2].collect{|i| ids[i] }
Any thoughts?
1 Answer