Filling instance variables in rspec tests

I have a class that has the following initialization method.

def initialize(my_var) @my_var = my_var end 

and I want to test a method that then does something with @my_var

 def split @my_var.split(",") end 

how do I change @my_var before testing that it returns an array correctly?

Is this possible if you do not have access for @my_var ?

+8
ruby rspec stubbing
source share
1 answer

This is not like good practice. Rspec should test the behavior of the interface of your classes and models, and not the internal implementation (which instance variables undoubtedly exist). There are ways to do this, but are you sure you don't want to have an accessor for this variable?

Anyway, you can use my_object.instance_variable_get("@my_var") and my_object.instance_variable_set("@my_var", value) to control the variable.

+25
source share

All Articles