[英]How to test records order in Rails?
我发现测试来自数据库的记录是否正确排序是非常冗长和乏味的。 我正在考虑使用数组'=='方法来比较两个搜索数组。 数组的元素和顺序必须相同,所以它似乎很合适。 问题是,如果缺少元素,即使严格按顺序排序,测试也会失败。
我想知道是否有更好的方法......
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
我没有遇到过很好地执行此操作的内置方法,但这里有一种方法可以检查对象数组是否按成员排序:
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
当我问这个问题时,我遇到了我想要的东西。 使用each_cons方法,它使测试非常整洁:
assert Person.all.each_cons(2).all?{|i,j| i.name >= j.name}
我认为对你的记录选择进行排序会给你一个更合适的有序结果集,事实上它总能很好地订购你的结果
通过这种方式,我认为你不需要数组==方法
HTH
sameera
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.