使用 minitest 在 rails 中按子句测试顺序的通用方法
generic way of testing order by clause in rails using minitest
我在模型中有一个默认范围定义如下:
default_scope { order(created_at: :desc) }
测试定义如下:
class ItemTest < ActiveSupport::TestCase
def setup
@first_item = items(:one)
@second_item = items(:two)
@third_item = items(:three)
@fourth_item = items(:four)
end
test "items should be ordered by time they got created ( default scope)" do
assert_equal [@fourth_item,@third_item, @second_item, @first_item], Item.all
end
和赛程:
one:
created_at: 2017-06-06 00:00:00 -0700
two:
created_at: 2017-06-06 00:00:02 -0700
three:
created_at: 2017-06-06 00:00:09 -0700
four:
created_at: 2017-06-06 00:00:30 -0700
测试通过但是,每次我向上述夹具文件添加新夹具时,测试都会失败,我必须添加assert_equals
语句中数组的新项目。
我试过this answer,这看起来很普通,但当它假设失败时测试仍然通过
items = Items.first(3) # and items.first(3).reverse still passes as well :(
assert_equals [items[0], items[1], items[2]], items
但不幸的是,即使我将顺序更改为 ASC
它应该会失败,测试也会通过。
是否有通用的方法来测试特定数量的商品订单?
我用minitest
您的测试是检查您的对象数组是否按给定属性排序。使用 each_cons 允许您一次枚举 n 个连续元素的数组。 each_cons doc
assert (Item.all.each_cons(2).all?{|a,b| a.created_at >= b.created_at})
我在模型中有一个默认范围定义如下:
default_scope { order(created_at: :desc) }
测试定义如下:
class ItemTest < ActiveSupport::TestCase
def setup
@first_item = items(:one)
@second_item = items(:two)
@third_item = items(:three)
@fourth_item = items(:four)
end
test "items should be ordered by time they got created ( default scope)" do
assert_equal [@fourth_item,@third_item, @second_item, @first_item], Item.all
end
和赛程:
one:
created_at: 2017-06-06 00:00:00 -0700
two:
created_at: 2017-06-06 00:00:02 -0700
three:
created_at: 2017-06-06 00:00:09 -0700
four:
created_at: 2017-06-06 00:00:30 -0700
测试通过但是,每次我向上述夹具文件添加新夹具时,测试都会失败,我必须添加assert_equals
语句中数组的新项目。
我试过this answer,这看起来很普通,但当它假设失败时测试仍然通过
items = Items.first(3) # and items.first(3).reverse still passes as well :(
assert_equals [items[0], items[1], items[2]], items
但不幸的是,即使我将顺序更改为 ASC
它应该会失败,测试也会通过。
是否有通用的方法来测试特定数量的商品订单?
我用minitest
您的测试是检查您的对象数组是否按给定属性排序。使用 each_cons 允许您一次枚举 n 个连续元素的数组。 each_cons doc
assert (Item.all.each_cons(2).all?{|a,b| a.created_at >= b.created_at})