How to check the order of records in Rails?

I find it very verbose and tedious to check if the entries from the database are ordered correctly. I think using the array method '==' to compare two query arrays. The elements of the array and the order must be the same so that they look good. The problem is that if the elements are missing, the test will fail, even if they are strictly ordered properly.

I wonder if there is a better way ...

+5
source share
4 answers

I came across what I was looking for when I asked this question. Using the each_cons method , it makes the test very neat:

assert Person.all.each_cons(2).all?{|i,j| i.name >= j.name}
+1
source

Rails 4

app/models/person.rb

default_scope { order(name: :asc) }


test/models/person.rb

test "people should be ordered by name" do
  xavier = Person.create(name: 'xavier')
  albert = Person.create(name: 'albert')
  all    = Person.all
  assert_operator all.index(albert), :<, all.index(xavier)
end

3

app/models/person.rb

default_scope order('name ASC')


test/unit/person_test.rb

test "people should be ordered by name" do 
  xavier = Person.create name: 'xavier'
  albert = Person.create name: 'albert'
  assert Person.all.index(albert) < Person.all.index(xavier)
end
+4

, , :

class MyObject
  attr_reader :a

  def initialize(value)
    @a = value
  end
end

a = MyObject.new(2)
b = MyObject.new(3)
c = MyObject.new(4)

myobjects = [a, b, c]

class Array
  def sorted_by?(method)
    self.each_cons(2) do |a|
      return false if a[0].send(method) > a[1].send(method)
    end
    true
  end
end

p myobjects.sorted_by?(:a) #=> true

, - :

test "people should be ordered by name by default" do 
  people = Person.all
  assert people.sorted_by?(:age)
end
+3
source

I think that sorting your records will give you a more correct ordered set of results, and it is actually always useful to order your results.

So, I think you do not need the array == method

NTN

Sameera

-3
source

All Articles