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.

More hashes

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.

reference: http://guides.rubyonrails.org/

Got any tips for working with Rspec controller specs? Leave a comment below.

« Previous Post
The year in review (2015)
Next Post »
Recovering from common Ruby on Rails errors and pitfalls

Join the conversation

comments powered by Disqus