If you have ever tried to write functional tests for a controller, you will know that they can be a little tricky. One such trip up point that I ran into was accessing instance variables from within the controller spec. You can't just use
expect(@variable).to be_valid because
@variable is an instance variable and won't be defined in your spec's scope.
Rspec and hashes
Instead Rails provides a number of hash objects for easier functional testing. To grab the instance variable one only needs to use the following format
assigns(:variable). This will grab the
@variable from the controller so you can use it in your tests.
There are a total of 4 hashes that can be utilized in your tests
- assigns - Any objects that are stored as instance variables in actions for use in views.
- cookies - Any cookies that are set.
- flash - Any objects living in the flash.
- session - Any object living in session variables.
Got any tips for working with Rspec controller specs? Leave a comment below.