Reputation: 107
I have trouble understanding a chunck of code on a book I'm reading.
Here's the code:
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
form the ruby documentation I got:
assert_equal(exp, act, msg = nil)
Fails unless exp == act printing the difference between the two, if possible.
am I right to assume that the line:
assert_equal "must be greater than or equal to 0.01" ,
means:
assert_equal ("must be greater than or equal to 0.01", , ) #with no act or msg.
also, can someone explain what array is the following line using and what for?
product.errors[:price].join('; ' )
I can't grasp where's the array and what is the author achieving by joining.
Thanks in advance for any information.
The book is: Agile Web Development with Rails 4th Edition
Upvotes: 3
Views: 2053
Reputation: 13077
The full assertion is in one line as follows :
assert_equal "must be greater than or equal to 0.01" , product.errors[:price].join('; ' )
Here, exp = "must be greater than or equal to 0.01"
and act = product.errors[:price].join('; ' )
product.errors[:price]
is an array, taking in multiple error messages.
Chaining .join(';')
to it is making all the error messages joined together with a ';' as a separator.
In this case, there is only one error ("must be greater than or equal to 0.01"
) and hence the join method is just returning the same value without adding a separator. Hence the assertion should pass.
Example to illustrate the behavior of join(';')
in this case:
> ['a', 'b'].join(';')
=> "a;b"
> ['a'].join(';')
=> "a"
Upvotes: 2