8

I have a class which has the following initialise method.

def initialize(my_var)
  @my_var = my_var
end

and I want to test the method which then does something to @my_var

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

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

Is this possible without having an accessor for @my_var?

1 Answer 1

25

This doesn't sound like a correct practice. Rspec should be testing the interface behavior of your classes and models - not the internal implementation (of which instance variables undoubtedly are). There are ways to do this, but are you sure you don't want to have an accessor for that variable?

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

Sign up to request clarification or add additional context in comments.

2 Comments

the reason i'm doing this is that my initialize method is reading from file, what I'm trying to do is stub File and write the expected processed data from that file without needing a file to support my tests. I can then skip that initialize method for testing any other methods in my class.
@JosephLeBrech, you can also try using StringIO instead of file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.