ruby - How to check if the class instantiated correctly -
say have class:
class product def initialize(v) @var = v end end
and test rspec whether instantiation of class went alright. should tested within class or unit testing, , how can that?
if initializer simple, it's not worth test it. on other hand, if you're adding parameter checking or other logic in initializer, might thought test out.
most of time, practice in case raise illegalargumenterror if parameter wrong. in case, can create sure initializing object did (or did not) raise error.
if you're doing more convoluted stuff, might want check value of instance variables. don't think using attr_reader
thought this, think changing class implementation testing purposes bad idea. instead, utilize #instance_variable_get
read variable.
class foo def initialize(mandatory_param, optional_param = nil) raise illegalargumenterror.new("param cannot #{param}") if mandatory_param == 42 @var1 = mandatory_param @var2 = optional_param unless param.is_a? string end end describe foo "should not take 42 argument" expect { foo.new(42, 'hello') }.to raise_error(illegalargumenterror) end "should set var2 if it's not string" f = foo.new('hello', 1) f.instance_variable_get(:@var2).should eq 1 end "should not set var2 if it's string" f = foo.new('hello', 'world') f.instance_variable_get(:@var2).should be_nil end end
ruby oop testing
No comments:
Post a Comment