首页 > 解决方案 > 用于断言集合中多个对象的属性的更好的失败消息

问题描述

为了断言该对象具有预期的属性,我提出了自定义方法

def be_active_sales_order_with(quantity)
  expected = {
    :order_type => "sales",
    :activated_at => be_within(1.minute).of(Time.current),
    :quantity => quantity
  }

  have_attributes(expected)
end

当上述方法与一个对象一起使用时,失败的消息会提供格式清晰的差异,哪个属性的值与预期的不同。

失败消息:

预期 # 有属性 {:order_type => "sales", :activated_at => (在 2019-11-26 15:56:17 的 300 以内), :quantity => 3} 但有属性 {:order_type => "销售”, :activated_at => 2019-11-24 15:56:17.000000000, :quantity => 3}
Diff:
@@ -1,5 +1,5 @@
:order_type => "销售",
-:activated_at = >(在 2019-11-26 15:56:17 的 300 以内),
+:activated_at => 2019-11-24 15:56:17.000000000,
:quantity => 3,

it "creates single order" do
   # configuration for single order

   orders = create_order.call(quantity: 3)

   expect(orders.only).to be_active_sales_order_with(3)
end

但是对于可以创建多个订单的情况,如果没有调试失败的测试,则难以阅读的失败消息。

it "creates multiple orders" do
   # configuration for multiple order

   orders = create_order.call(quantity: 3)

   expect(orders).to contain_exactly(
     be_active_sales_order_with(3),
     be_active_sales_order_with(3),
     be_active_sales_order_with(3)
   )
end

失败消息:

包含的预期集合:[(具有属性 {:order_type => “sales”,:activated_at =>(在 2019-11-26 15:56:17 的 300 以内),:quantity => 3})]
实际包含的集合: [#Order id: 885385454, customer_id: 367693892, topic: nil, created_at: "2019-..., segment_key: "9bf937d687eaff19", stock_id: nil, notify_by: nil, use_discount: false, user_id: 548091186]
缺少的元素是: [(有属性 {:order_type => "sales", :activated_at => (在 2019-11-26 15:56:17 的 300 以内), :quantity => 3})]
额外的元素是:[#订单 id:885385454,customer_id:367693892,主题:nil,created_at:“2019-...,segment_key:“9bf937d687eaff19”,stock_id:nil,notified_by:nil,use_discount:false,user_id:548091186]

如何构建更具可读性的消息,提供预期和实际对象属性之间的可读差异

标签: rubyrspec

解决方案


推荐阅读