在我的用户控制器中。我有
module Api;module V1
class UsersController < ApplicationController
skip_before_action :authenticate_user_from_token!, only: [:create]
before_action :set_user, only: [:destroy, :update, :show]
before_action :authorize_user, except: :create
def create
#TODO : fix for simultaneous account and registration create
@user = User.new user_params
@user.save!
render json: @user,status: :ok and return
end
private
def set_user
@user = User.find(params[:id])
end
def authorize_user
unless set_user == current_user
render json:{message: "you are not authorized."}, status: 401
end
end
end
end;end
现在我的问题是我的rspec用户控件
RSpec.describe UsersController, type: :controller do
it "can create user" do
post :create, user: {email: "ad@ad.ad",username: "add", name: "dad",
password: "password", password_confirmation: "password",
account:{company: "caaad"}}, :formate =>:json
puts response
end
端 但它给我以下错误
Failure/Error: render json: @user, status: :ok and return
NoMethodError:
undefined method `authenticate' for nil:NilClass
我的代码非常简单,测试的逻辑不多。 为什么不工作? 我甚至试图添加
config.include Devise::TestHelpers, :type => :controller
在spec_helper中,但仍无法正常工作。请告诉我我错过了什么?
虽然控制器代码是正确的,因为它正在使用正常的Curl请求。
在我的用户模型中
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
after_create :update_access_token!
def update_access_token!
self.access_token = "#{self.id}:#{Devise.friendly_token}"
save!
end
端
答案 0 :(得分:0)
测试正在进行,让我怀疑应用程序中还有另一个UsersController
,因为我希望您的规范看起来像这样:
RSpec.describe Api::V1::UsersController, type: :controller do
it "can create user" do
post :create, user: {email: "ad@ad.ad",username: "add", name: "dad",
password: "password", password_confirmation: "password",
account:{company: "caaad"}}, :formate =>:json
puts response
end
end
如果仍然导致错误,我建议您查看this SO answer