Rspec 2.7 access controller session in spec before making request

痴心易碎 提交于 2019-11-29 09:00:45

问题


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?


回答1:


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 => 'example@gmail.com', :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.




回答2:


Try this:

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


来源:https://stackoverflow.com/questions/8043956/rspec-2-7-access-controller-session-in-spec-before-making-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!