简体   繁体   中英

How to test records order in Rails?

I find very verbose and tedious to test if records coming from the database are correctly ordered. I'm thinking using the array '==' method to compare two searches arrays. The array's elements and order must be the same so it seems a good fit. The issue is that if elements are missing the test will fail even though they are strictly ordered properly.

I wonder if there is a better way...

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

Rails 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

I haven't come across a built-in way to do this nicely but here's a way to check if an array of objects is sorted by a member:

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

Then you can use it using something like:

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

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}

I think having your record selection sorted will give you a more proper ordered result set, and in fact its always good to order your results

By that way I think you will not need the array == method

HTH

sameera

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM