chris
chris

Reputation: 6823

Rspec test if a session variable was set in a controller action

I have an rspec test that posts to an action. In the action, a session variable is definitely set, however in my controller test, the session hash is empty. How do I check in an Rspec test to see if the controller set the session variable to the right value?

Upvotes: 16

Views: 16953

Answers (3)

Eduardo Santana
Eduardo Santana

Reputation: 6110

See this. The main problem is that the variable session is not accessible from the test code. To solve it, add the fowling lines at spec/spec_helper.rb:

def session
  last_request.env['rack.session']
end

Upvotes: 4

RunFor
RunFor

Reputation: 555

Do you use any before_filter in your controller? This could be the case, if before_filter changes the flow, and your code with assigning a variable to the session has not even evaluated.

For example you may have this line in your controller:

# ...
  before_filter :authenticate_user!
# ...

That means if you are not signed in, you will never enter any method in this controller. So the session variable will be empty.

Upvotes: 0

Billy Chan
Billy Chan

Reputation: 24815

You can access session directly in rspec like this: session[:key]. Just compare that with the value you want.

Upvotes: 22

Related Questions