undefined方法解压缩为nil:渲染JSON时的NilClass

时间:2017-01-11 13:19:39

标签: json ruby rspec ruby-on-rails-5 rails-api

我正在使用Rails 5 API应用程序,并且在尝试渲染json时遇到了麻烦。拿那个简单的控制器:

module Api
  module V1
    class UsersController < ApplicationController
      def sign_up
        @user = User.new user_params
        if @user.save
          render json: {status: :ok, user: @user.to_json }
        else
          render json: { status: :error, errors: @user.errors }, status: :unprocessable_entity
        end
      end
    end
  end
end

当我使用简单的规范测试此请求时:

RSpec.describe Api::V1::UsersController, type: :controller do

  context 'As an unregistered user' do
    context 'signing up with valid params' do
      let(:valid_params) do
        { name: 'Test User', email: 'test@test.com', password: '123456789', password_confirmation: '123456789' }
      end

      it 'returns a 200 status' do
        post :sign_up, params: { user: valid_params }
        expect(response.status).to eq 200
      end
    end
  end
end

我收到一个错误:

Failures:

  1) Api::V1::UsersController As an unregistered user signing up with valid status returns a 200 status
     Failure/Error: render json: {status: :ok, user: @user.to_json }

     NoMethodError:
       undefined method `unpack' for nil:NilClass
     # ./app/controllers/api/v1/users_controller.rb:10:in `sign_up'
     # ./spec/controllers/api/v1/users_controller_spec.rb:15:in `block (4 levels) in <top (required)>'

我没有使用任何改变渲染的宝石,所以我真的迷失了可能出现的问题。提前谢谢。

0 个答案:

没有答案