2

I am new to rails and serializers.I am using active model serializer gem for serialization.

One of the attributes uses devise helper method 'current_user'.It works fine.But While running the spec using rspec i get an error undefined local variable or method 'current_user'.Please can anyone help me to solve this?

I am using rails 3.2 and rspec 2

junil
  • 758
  • 5
  • 12
  • maybe this will help you http://stackoverflow.com/questions/23793597/how-to-access-devise-current-user-in-a-rspec-feature-test/28047750#28047750 – RustemMazitov Jan 20 '15 at 14:29

2 Answers2

3

This question is old, but I ran into the same problem, although already using Devise Helpers.

I use Ruby on Rails 4.2, Rspec 3.5, Active Model Serializers 0.8.3.

I have Devise::Test::ControllerHelpers included in Rspec, and can use sign_in in my spec file, yet I had NameError: undefined local variable or method 'current_user' when calling the serializer method that relied on current_user. Note that the controller use current_user fine.

Here is the spec file (not working) :

describe ArticleController do
  before :each do 
    @article = create(:article)
  end
  describe 'PUT #update' do
    context "as user" do
      before :each do 
        @u = create(:user)
        sign_in @u
      end

      it 'sets the seen status' do
        put :update, id: @article, article: { seen: true }
        expect(ArticleSerializer.new(@article.reload).seen).to eq(true)
      end
    end
  end
end

and the Serializer :

class ArticleSerializer < ActiveModel::Serializer
  attributes :id, :text, :seen

  def seen
    object.article_user_seen.find_by( user_id: current_user.id ).try(:seen) || false
  end

end

I modified the test, using options scope and scope_name when creating the serializer instance. Thanks to this guide : https://github.com/rails-api/active_model_serializers/blob/master/docs/general/serializers.md

Working test below :

describe ArticleController do
  before :each do 
    @article = create(:article)
  end
  describe 'PUT #update' do
    context "as user" do
      before :each do 
        @u = create(:user)
        sign_in @u
      end

      it 'sets the seen status' do
        put :update, id: @article, article: { seen: true }
        expect(ArticleSerializer.new(@article.reload, scope: @u, scope_name: :current_user).seen).to eq(true)
      end
    end
  end
end
Quentin
  • 1,085
  • 1
  • 11
  • 29
1

first you should inlcdue include Devise::TestHelpers in your rspec file , then you should create a user and sign in it . like this code :

@user = create(:user)

sign_in @user

  • 1
    Now it shows Failure/Error: sign_in @user NoMethodError: undefined method `env' for nil:NilClass – junil Aug 09 '13 at 10:26