[英]What is an appropriate way to test function input in ruby
我有幾個ruby函數,想檢查輸入是否正確以及輸入是否有意義。 什么是明智的做法?
這是一個示例,其中包含我所擁有的功能之一以及我想檢查的內容
# Converts civil time to solar time
# civilT: Time object
# longitude: float
# timezone: fixnum
def to_solarT(civilT,longitude,timezone)
# pseudo code to check that input is correct
assert(civilT.class == Time.new(2013,1,1).class)
assert(longitude.class == 8.0.class)
assert(timezone.class == 1.class)
# More pseudocode to check if the inputs makes sense, in this case
# whether the given longitude and timezone inputs make sense or whether
# the timezone relates to say Fiji and the longitude to Scotland. Done
# using the imaginary 'longitude_in_timezone' function
assert(longitude_in_timezone(longitude,timezone))
end
我在這里找到了一個相關的問題: 如何在ruby代碼中放入斷言 。 這是走的路還是有更好的方法來測試Ruby中的功能輸入?
你不應該這樣。 Ruby在很大程度上依賴於鴨子輸入。 也就是說,如果它像鴨子一樣嘎嘎叫,那就是鴨子。 即只使用您收到的對象,如果它們正確響應,就可以了。 如果沒有,則可以挽救NoMethodError並顯示適當的輸出。
assert
不是標准的Ruby方法,並且經常由測試框架使用,因此我認為將其放入代碼中不是很好。 同樣,創建要檢查其參數的類的實例也沒有意義。 更直接地說,
def to_solarT civilT, longitude, timezone
raise "Argument error blah blah" unless Time === civilT
raise "Argument error blah blah" unless Float === longitude
raise "Argument error blah blah" unless Fixnum === timezone
...
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.