I'm trying to test ordering collection by created_at
. As it's timestamp with precision to the second, when I create 10 records they have the same created_at
value which leads me to inconsistent response. So what I'm doing here is I set created_at
field manually like
5.times do |t|
create(:model, created_at: Time.current.advance(days: -1*(t+1))
end
and it set created_at
just fine but when I do
Model.all.order(created_at: :desc)
it just ignores it and put in ASC
order.
Is there any way to test this order as well?
Thanks
It's possible that the timestamp you're providing isn't being saved, and that Rails is using its own internal timestamps as the objects are created. You might try:
5.times do |t|
thing = create(:model)
thing.update_column(:created_at, Time.current.advance(days: -1*(t+1))
end
This will bypass any validation on the model and you should be saving the correct timestamps, and you should then be able to order them as expected.
You can test by saving results of the query in the variable results
and then something like:
expect(results[0].created_at < results[1].created_at).to be true
Another thing you might try is YourModel.unscope.where(...).order(created_at: :desc)
. There may be a scope that you can't see that is affecting the order.