Testing Rails functions with a registered user (undefined method 'session')

I write function specifications with rspec and want to skip the login step every time. Users authenticate with omniauth (without development) and the session[:user] variable, and then refer to staying on the system. I want to be able to directly set the session variable, if possible:

 require 'spec_helper' describe "My page" do it "has what I want on it when logged in" do user = FactoryGirl.create(:user) session[:user] = user.id visit my_path page.should have_content "Foobar" end end 

but it gives

  Failure/Error: session[:user] = user.id NameError: undefined local variable or method `session' for #<RSpec::Core::ExampleGroup::Nested_1:0x007fd13456d170> 

Is there a way to set the session variable directly so that I can avoid the login step in most tests?

+7
ruby-on-rails ruby-on-rails-3 session rspec omniauth
source share
2 answers

The rack_session_access hard drive works well: https://github.com/railsware/rack_session_access

In this case, the test becomes:

 require 'spec_helper' describe "My page" do it "has what I want on it when logged in" do user = FactoryGirl.create(:user) page.set_rack_session(user: user.id) visit my_path page.should have_content "Foobar" end end 
+9
source share

If it was a controller specification, you could simulate a login like this:

 request.session[user_id] = user.id 

as indicated in How to simulate login with RSpec? . However, since this is a function specification, I do not believe that setting up a session is directly possible.

0
source share

All Articles