Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 477
Karan Avatar asked Sep 01 '12 09:09

Karan


2 Answers

If you include the Confirmable module in your User model (or other devise-authenticatable model), then the test @user you create must be confirmed for the sign_in to take effect:

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

(I see that this wasn't your issue, but perhaps another reader shall benefit from it.)

like image 54
JellicleCat Avatar answered Sep 23 '22 18:09

JellicleCat


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!

like image 34
Tyler Gannon Avatar answered Sep 21 '22 18:09

Tyler Gannon