Ruby-on-rails – Testing Sessions in Rails 3 with Rspec & Capybara

capybararspecruby-on-railssession

I'm trying to write integration tests with rspec, factory_girl & capybara. I also have cucumber installed, but I'm not using it (to my knowledge).

I basically want to prepopulate the db with my user, then go to my home page and try to log in. It should redirect to user_path(@user).

However, sessions don't seem to be persisted in my /rspec/requests/ integration tests.

My spec: /rspec/requests/users_spec.rb

require 'spec_helper'

describe "User flow" do

  before(:each) do
    @user = Factory(:user)
  end

  it "should login user" do

    visit("/index")

    fill_in :email, :with => @user.email
    fill_in :password, :with => @user.password
    click_button "Login"
    assert current_path == user_path(@user)
  end
end

Returns:

Failures:

  1) User flow should login user
     Failure/Error: assert current_path == user_path(@user)
     <false> is not true.
     # (eval):2:in `send'
     # (eval):2:in `assert'
     # ./spec/requests/users_spec.rb:16

Instead, it redirects to my please_login_path – which should happen if the login fails for any reason (or if session[:user_id] is not set).

If I try to put session.inspect, it fails as a nil object.

If I try to do this in the controller tests (/rspec/controllers/sessions_spec.rb), I can access the session with no problem, and I can call session[:user_id]

Best Answer

If you are using Devise, you'll need to include Warden::Test::Helpers (right after the require of spec_helper is a good place) as outlined in the warden wiki.

The call to session is returning nil because capybara doesn't provide access to it when running as an integration test.

Related Topic