当条件开始变得太长时,我总是遇到麻烦。曾经有帮助的事情是将其中一些包装成 individual methods
。这条路线至少会为您提供几个可以在测试中存根的公共方法。
def age
return unless dob
Date.today - dob
end
def age_at_start
return unless valid_age_at_start(start_date, dob)
start_date - dob
end
def compensation
return unless valid_compensation(age_at_start, time_worked, salary, staff_rating)
some_calculation(time_worked, age_at_finish, salary, staff_rating)
end
def valid_age_at_start(start_date, dob)
start_date && dob
end
def valid_compensation(age_at_start, time_worked, salary, staff_rating)
age_at_start && time_worked && salary && staff_rating
end
或者您可以创建一个仅验证您的论点的方法:
def age
return unless dob
Date.today - dob
end
def age_at_start
return unless valid_arguments?(start_date, dob)
start_date - dob
end
def compensation
return unless valid_arguments?(age_at_start, time_worked, salary, staff_rating)
some_calculation(time_worked, age_at_finish, salary, staff_rating)
end
private
def valid_arguments?(*args)
args.each do |arg|
return false unless arg
end
return true
end
诚然,这两条路线仍然有点难看。