2

Я боролся с undefined method 'authenticate' for nil:NilClass для моих запросов, используя сериализатор (Rspec).active_model_serializer + devise + rspec

апи/users_controller_spec.rb

require 'rails_helper' 

describe Api::V1::UsersController, type: :controller do 
    describe "GET #show" do 
    context "with valid credentials" do 
     let!(:application) { create(:doorkeeper_application) } # OAuth application 
     let!(:user)  { create(:user) } 
     let!(:token)  { create(:doorkeeper_access_token, application_id: application.id, resource_owner_id: user.id) } 
     before do 
     allow(controller).to receive(:doorkeeper_token) {token} 
     end 

     context 'and valid request' do 
     before(:each) do 
      get :show, format: :json 
      @json = JSON.parse(response.body) 
     end 

     it "returns the user with 'id'" do 
      expect(@json["id"]).to_not be_nil 
     end 
     end 
    end 
    end 
end 

сериализаторов/user_serializer.rb

class UserSerializer < ActiveModel::Serializer 
    attributes :id, :uid, :name, :email 
end 

ответ

1

Оказывается, все, что мне было нужно, чтобы добавить serialization_scope :view_context к моему ApplicationController, но я только обнаружил это, когда наблюдая за потрясающим железнодорожным сообщением о камне: http://railscasts.com/episodes/409-active-model-serializers?view=asciicast

Отредактировано

Не используйте active_model_serializer> 0.9.x, иначе он будет разорвать производство. https://github.com/rails-api/active_model_serializers/commit/0d31e72d2211b6bf7f0b0420139c4b370d6e986e https://github.com/rails-api/active_model_serializers/issues/139

+1

Спасибо! Это сработало для меня в моем проекте Rails 4.2.1. Странно то, что мне не нужно было устанавливать это в моем проекте Rails 5. : / – CalebHC