assert_equal Syntax

3
我有困难理解我正在阅读的一本书中的一段代码。
以下是代码:
test "product price must be positive" do
  product = Product.new(:title => "My Book Title", :description => "yyy", :image_url => "zzz.jpg")
  product.price = -1

  assert product.invalid?
  assert_equal "must be greater than or equal to 0.01", product.errors[:price].join('; ' )

  product.price = 0
  assert product.invalid?

  assert_equal "must be greater than or equal to 0.01", product.errors[:price].join('; ' )
  product.price = 1
  assert product.valid?
end

从Ruby文档中我得到的是:
assert_equal(exp, act, msg = nil)
如果可能的话,打印两者之间的差异,除非exp == act。
我是否正确地认为以下行:
assert_equal "must be greater than or equal to 0.01" ,
意味着:
assert_equal("must be greater than or equal to 0.01", , ) # 没有act或msg。
此外,有人能解释一下下面这行代码使用的数组是什么,以及它的用途是什么吗? product.errors[:price].join('; ')
我无法理解数组在哪里,作者通过连接实现了什么。
谢谢您提前提供的任何信息。
该书是《Rails敏捷Web开发第4版》。
1个回答

2
完整的断言如下所示:
 assert_equal "must be greater than or equal to 0.01" , product.errors[:price].join('; ' )

在这里,exp = "必须大于或等于0.01"act = product.errors[:price].join('; ' ) product.errors[:price] 是一个数组,包含多个错误信息。
在其后链式调用.join(';')会将所有错误消息使用分号';'作为分隔符连接在一起。
在本例中,只有一个错误消息("必须大于或等于0.01"),因此join方法返回的值与未加分隔符的值相同。因此断言应该通过。
以下是说明在本例中join(';')的行为的示例:
> ['a', 'b'].join(';')
=> "a;b" 

> ['a'].join(';')
=> "a" 

2
错误是一个数组类型的对象,因此需要使用 join 将它们渲染成字符串。 - tadman
非常感谢您的回答,因为我无法理解那段代码,所以我拒绝继续阅读这本书。 - Will Raben

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接