ruby rspec:测试示例数组

u3r8eeie  于 2022-11-04  发布在  Ruby
关注(0)|答案(1)|浏览(166)

我正在尝试创建rspec测试来测试一个示例数组。具体地说,我想验证数组中每个示例的某些属性。有没有办法使用rspec来测试这个场景?
例如,假设我想要验证下列数组:

  1. [#<Car id:1, buy_date: "2022-10-10", model: "Ford">,
  2. #<Car id:2, buy_date: "2021-01-10", model: "Ferrari">,
  3. #<Car id:3, buy_date: "2022-03-12", model: "Toyota">]

作为我的测试,我想检查buy_date是否正确。我尝试了下面的expect语句,但我认为它不适用于示例数组,所以当我期望测试通过时,测试失败了。

  1. expect(cars).to include([
  2. have_attributes(
  3. buy_date: "2022-10-10"
  4. ),
  5. have_attributes(
  6. buy_date: "2021-01-10"
  7. ),
  8. have_attributes(
  9. buy_date: "2022-03-12"
  10. )
  11. ])

我也尝试过用match_array代替include,但结果是一样的。
如何使用rspec来实现这一点呢?

anauzrmj

anauzrmj1#

include匹配器的作用是检查被测试的集合中是否包含传递的值,所以你要检查car数组中是否有元素是一个数组,包含3个具有给定属性的对象。
这是因为你可以有一个数组的数组,你应该能够测试一个给定的数组是否作为一个值包含在数组的数组中。
要测试多个值,必须将它们作为多个参数传递:

  1. expect(cars).to include(
  2. have_attributes(
  3. buy_date: "2022-10-10"
  4. ),
  5. have_attributes(
  6. buy_date: "2021-01-10"
  7. ),
  8. have_attributes(
  9. buy_date: "2022-03-12"
  10. )
  11. )

为了提高可读性,RSpec提供了多个别名:

  1. expect(cars).to include(
  2. an_object_having_attributes(
  3. buy_date: "2022-10-10"
  4. ),
  5. an_object_having_attributes(
  6. buy_date: "2021-01-10"
  7. ),
  8. an_object_having_attributes(
  9. buy_date: "2022-03-12"
  10. )
  11. )

现在,你是以这种方式使用include,还是match_array的区别在于你是想允许它包含其他元素,还是你想让它包含那些元素。
此外,就可读性而言,我更愿意将它与多个匹配器结合使用:

  1. expect(cars).to
  2. include(an_object_having_attributes(buy_date: "2022-10-10"))
  3. .and include(an_object_having_attributes(buy_date: "2021-01-10"))
  4. .and include(an_object_having_attributes(buy_date: "2022-03-12"))
展开查看全部

相关问题