I’ve used instance_variable_set to put read-only attributes to known state so that I can test some methods that check for instance variable values and do something.
I understand about not testing private methods, so would this be considered a wrong approach as well?
How is the instance variable set from within your class? If it’s passed to the constructor, you should initialize a new instance with the desired value passed in.
If it’s calculated from internal state you should initialize the instance with values such that the calculation does what you want. If this calculation is complicated, consider extracting another object to do this work that can be unit tested on its own.
If it’s calculated using some external state, then use stubs to implement the desired behavior on those external objects.
My case was when an instance variable was being updated internally, and there were some methods that do things differently based the value of the instance variable. That certainly made testing very hard. Maybe instance variable can be stubbed as well?
I would NOT suggest stubbing an instance variable. That’s stubbing the system under test, and you should not do that.
If a single instance variable changes the behavior of several methods in your class you should take a long look at your class. Are you sure it’s one class? Would it be better to break it up into several classes that all work in a known way and then decide which type of class to create using that instance variable?
I think I totally just answered my own question when writing this lol… but here goes anyway…
Just to clarify @derekprior - stubbing an instance variable should be OK if it’s in fact an external object that’s getting passed into the constructor via dependency injection right?
After reading that article, that seems to be the case and now thinking about it more, it makes sense since that external object should not be considered part of the SUT (system under test) and should be tested separately anyway.
@yang_chung check out Sandi Metz’s Magic Tricks of Testing, I believe it may be relevant to what you’re dealing with. It’s another great talk by Sandi.