简体   繁体   English

如何测试数据库记录是否按 id 排序?

[英]How to test if database records are ordered by id?

I'm testing a JSON API.我正在测试 JSON API。 And up until recently I assumed the records are returned ordered by id.直到最近,我还认为记录是按 id 排序返回的。 But when Posts.all turned into Posts.where(user_id: params[:user_id]) , it broke the following test:但是当Posts.all变成Posts.where(user_id: params[:user_id]) ,它破坏了以下测试:

it 'takes "limit" param' do
  post1 = create :post
  post2 = create :post, user_id: post1.user_id
  get user_posts_path(post1.user_id, limit: 1)
  expect(response.body).to be_json_eql([{id: post1.id}].to_json).including(only: :id)
end

I can probably add the following test:我大概可以添加以下测试:

it 'returns records ordered by id' do
  post1 = create :post
  post2 = create :post, user_id: post1.user_id
  get user_posts_path(post1.user_id)
  expect(response.body).to be_json_eql([{id: post1.id}, {id: post2.id}].to_json).including(only: :id)
end

but it succeeds without adding .order(:id) to the controller.但它在没有将.order(:id)添加到控制器的情况下成功。 I'd like to make sure it's there.我想确保它在那里。 What do I do?我该怎么办?

The order is not guaranteed, so while you might get the behaviour of the results being ordered by id, it's not guaranteed, and you should not rely on it.顺序是不能保证的,所以虽然你可能会得到按 id 排序的结果的行为,但不能保证,你不应该依赖它。

See " Why is SSMS inserting new rows at the top of a table not the bottom? "请参阅“ 为什么 SSMS 在表格顶部而不是底部插入新行?

Also, as it mostly returns by id, your test will mostly succeed without the order set but it tells you nothing and is bad practice.此外,由于它主要通过 id 返回,因此您的测试在没有设置订单的情况下大部分会成功,但它什么也不告诉您,并且是不好的做法。

So, are you really asking if I do something that's not safe, how can I write a test to check if something bad happens as result?所以,你真的在​​问我是否做了一些不安全的事情,我怎么能写一个测试来检查结果是否会发生不好的事情?

I'm not sure why you would do that.我不确定你为什么要这样做。 You've got a potential intermittent bug that will appear when the database decides it wants to, on any environment.您有一个潜在的间歇性错误,当数据库决定要在任何环境中出现时,该错误就会出现。 Even if it doesn't happen in your testing environment it may happen in production, so it tells you nothing.即使它没有发生在您的测试环境中,它也可能发生在生产中,因此它不会告诉您任何信息。 Remove the bug by adding an order, then your test should pass through a known behaviour.通过添加订单来消除错误,然后您的测试应该通过已知行为。

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

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