이 질문은 오래,하지만 난 이미 고안 도우미를 사용하지만, 동일한 문제에 부딪쳤다.
Ruby on Rails 4.2, Rspec 3.5, Active Model Serializers 0.8.3을 사용합니다.
내가 고안 :: 시험 :: ControllerHelpers이 RSpec에 포함이 있고, 내 스펙 파일에
sign_in
을 사용할 수 있습니다, 아직
current_user
에 의존 시리얼 라이저 메서드를 호출 할 때 나는
NameError: undefined local variable or method 'current_user'
했다. 컨트롤러는
current_user
을 사용합니다.
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
과 시리얼 :
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
내가 시리얼 인스턴스를 만들 때 옵션
scope
및
scope_name
를 사용하여 테스트를 수정 한 다음
은 사양 (작동하지 않는) 파일입니다. 이 가이드 덕분에 아래
https://github.com/rails-api/active_model_serializers/blob/master/docs/general/serializers.md
작동 시험 :
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
어쩌면이 당신을 도울 것입니다 http://stackoverflow.com/questions/23793597/how-to-access-devise-current-user-in -a-rspec-feature-test/28047750 # 28047750 – RMazitov