簡體   English   中英

如何在Rails中測試記錄順序?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM