Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec 2.7 access controller session in spec before making request

I'm testing my controllers using Rspec and I can't seem to set the session variable of the current controller under test before making the request to the path. For example this works:

  describe "GET /controller/path" do
    it "if not matching CRSF should display message" do
      get controller_path

      request.session[:state] = "12334"
    end
  end

This doesn't work (i get an error saying session is not a method of Nil class):

      describe "GET /controller/path" do
        it "if not matching CRSF should display message" do
          request.session[:state] = "12334"
          get controller_path
        end
      end

Any ideas?

like image 895
Victor Blaga Avatar asked Nov 07 '11 23:11

Victor Blaga


2 Answers

With new version of RSpec this is done pretty nice, look:

describe SessionController do
  # routes are mapped as:
  # match 'login' => 'session#create'
  # get 'logout' => 'session#destroy'

  describe "#create" do
    context "with valid credentials" do
      let :credentials do
        { :email => '[email protected]', :password => 'secret' }
      end

      let :user do
        FactoryGirl.create(:user, credentials)
      end

      before :each do
        post '/login', credentials
      end

      it "creates a user session" do
        session[:user_id].should == user.id
      end
    end

    # ...
  end

  describe "#destroy" do
    context "when user logged in" do
      before :each do
        get "/logout", {}, { :user_id => 123 } # the first hash is params, second is session
      end

      it "destroys user session" do
        session[:user_id].should be_nil
      end

      # ...
    end
  end
end

You can also use simply request.session[:user_id] = 123 inside before(:each) block, but above looks pretty nicer.

like image 106
Dan K.K. Avatar answered Oct 29 '22 00:10

Dan K.K.


Try this:

describe "GET /controller/path" do
    it "if not matching CRSF should display message" do
      session[:state] = "12334"
      get controller_path
    end
  end
like image 43
Richard Avatar answered Oct 29 '22 02:10

Richard