I thought I’d share a git commit from today which I found quite interesting. It
is the adding of a to_str method to an Address value object. In the spec I
type check the return on to_str to make sure it is a String.
Add Address#to_str since address can easily be coerced in to a String
First the spec:
require'spec_helper'require'active_model'require'virtus'require_relative'../../app/models/address'describeAddressdodescribe'#to_s'doit'includes all lines comma delimited'doaddress=Address.new(:line_1=>'a',:line_2=>'b',:line_3=>'c',:postcode=>'d')address.to_s.should=='a, b, c, d'endit'excludes blank lines'doaddress=Address.new(:line_1=>'a',:line_3=>'c',:postcode=>'d')address.to_s.should=='a, c, d'endenddescribe'#to_str'doit'returns a string'doaddress=Address.new(:line_1=>'a',:postcode=>'b')address.to_str.shouldbe_instance_of(String)endendend
An object should only implementation to_str if it provides a superset of the
String API, in other words it can duck type to a String and be used in place of
Therefore in my spec the safest thing to do is to a type check to make sure the
reutrned object is a String.