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