20

I'm writing a rspec tests for my controller and i cannot find solution following problem. For one of the edge case tests I need to verify the value of one instance variable. How can i access it without having to define the accessor? By default the usual:

controller.variable.should == '3.15' 

doesn't work.

Defining

attr_reader :variable

just to make the tests pass would be silly and i'm sure that there is a more inteligent way.

1 Answer 1

44
controller.instance_variable_get(:var)

if you find yourself doing this, you might want to rethink your approach to information hiding so that you are testing essential behavior rather than incidental implementation details. Your tests should ensure that the "thing" functions as it should without being too tightly bound to the particular implementation.

EDIT: Isn't assigns(:var) the rails testing magic for doing the same thing with controllers?

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

6 Comments

Yeah probably you're right - i should test the results of the action instead of the implementation details. Thanks anyway.
to be fair, for controllers, instance variables are things that should be tested. I answered this question before coffee.
The question wasn't really relevant to exactly what I was doing, just needed to check for the existence of a controller's instance variable. @BenHughes, your answer (and subsequent answer) helped much. Thanks.
Use assigns (it's a free method, not controller.assigns), as instance_variable_get may have more restrictions than assigns. For example: 'event' is not allowed as an instance variable name, but assigns detects @event without any problem.
@BenHughes, thanks, it's something trivial to work out, but I would specify controller.instance_variable_get(:@var) and assigns(:var)
|

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.