【问题标题】:Rspec error while trying to create user with Devise token auth尝试使用设计令牌身份验证创建用户时出现 Rspec 错误
【发布时间】:2016-11-07 17:55:19
【问题描述】:

在我的用户控制器中。我有

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 

结束

【问题讨论】:

  • 能否发布完整的 users_controller.rb 和 users_controller_spec.rb
  • @oreoluwa 已编辑,请立即查看
  • 问题中的方法能解决你的问题吗?
  • @oreoluwa 它没有修复错误,但我知道错误不在我的代码中,它在设计和 rspec 配置中。

标签: ruby-on-rails ruby rspec devise


【解决方案1】:

首先测试正在进行,这让我怀疑应用程序中还有另一个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

【讨论】:

  • 谢谢您的回答。我在声明 Rspec.describe 之前设置了模块 Api;module V1,因此它击中了正确的 UserController。我正在编辑我的问题。
猜你喜欢
  • 1970-01-01
  • 2019-10-28
  • 1970-01-01
  • 2013-12-04
  • 2015-06-01
  • 2021-05-24
  • 2011-09-10
  • 2016-10-15
  • 1970-01-01
相关资源
最近更新 更多