[英]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 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 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 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 HTH
sameera sameera
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.