Search code examples
ruby-on-railstestingdevise

Devise Test Helper - sign_in does not work


For some reason, I can not get the devise helper method sign_in to work. current_user keeps on being null. Any idea what the problem could be?

Test:

  before :each do
    @user = FactoryGirl.create :user
    sign_in @user
  end

  describe "GET index" do
    it "assigns all subscribers as @subscribers" do
      subscriber = @user.subscribers.create! valid_attributes
      get :index
      assigns(:subscribers).should eq([subscriber])
    end
  end

Implementation:

  def index
    @subscribers = current_user.subscribers.all    <------- ERROR

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @subscribers }
    end
  end

Error:
 NoMethodError:
       undefined method `subscribers' for nil:NilClass

Any help is appreciated. Thanks!


Solution

  • Looks like you solved this, judging by your code. I have had this happen before, and for some reason it gets me every time.

    The rspec/rails scaffold for controller specs won't work with Devise::TestHelpers out of the box.

    get :index, {}, valid_session
    

    The valid_session call overwrites the session stuff that Devise sets up. Remove it:

    get :index, {}
    

    This should work!