8

I am using rspec and capybara for integration testing.

Is their a way to make session objects in request specs?

I have a view page in which I use a session object to check its value to display selective content.

The problem am facing is that I cannot create a session object in request spec. Here is an example of the view:

<% if session[:role] == "Role" %>
---content---
<% else %>
--content--
<% end %>

And inside my request spec

session[:role] = "Role"
visit my_path

But it throws me an error "undefined method `session' for nil:NilClass".

I also tried looking into creating session objects of capybara.But couldnt find anything.

Is their any workaround for this? I can not find anything related to this, it seems that it is not possible.A little help is really appreciated.

Anidhya Ahuja
  • 883
  • 7
  • 22

1 Answers1

3

The way you are supposed to do request specs is visit whatever URL the user would normally need to visit in order for that session variable to be set.

I don't know of any other way, other perhaps than setting the session cookie by hand. Capybara.current_session.driver.browser.set_cookie let's you do this but you would have to create the cookie value by hand.

Frederick Cheung
  • 83,189
  • 8
  • 152
  • 174
  • i tried this : cookies[:role] = "Coaching", Capybara.current_session.driver.browser.set_cookie(cookies[:role]) ,, but not working.what m i doing wrong? – Anidhya Ahuja Jan 04 '12 at 13:22
  • 1
    That won't set the session. You would need to reproduce how rails generates session cookies and use the output of that in the call to set_cookie. You're definitely off the beaten path here - like i said the usual approach is just to visit the page that sets the session – Frederick Cheung Jan 04 '12 at 13:30
  • in my case i sets these sessions in a private method in application controller. – Anidhya Ahuja Jan 04 '12 at 13:50
  • sure, but there must be some page you can view on the site that ends up calling that method. With a request spec you should be reproducing the interactions that a normal user would do with their browser to end up in the desired state – Frederick Cheung Jan 04 '12 at 14:05