2016-06-13 54 views
0

,所以我一直试图做一个基本的响应测试 - 用200和403。我不知道我需要添加任何东西..错误响应状态+设计+ factory_girl

accounts_spec。 RB

RSpec.describe Api::V1::AccountsController, :type => :controller do 
    describe "GET index no account" do 
    it "has a 403 status code" do 
     get :index 
     expect(response.status).to eq(403) 
    end 
    end 
    describe "GET index with account" do 
    login_user 
    it "has a 200 status code" do 
     get :index 
     expect(response.status).to eq(200) 
    end 
    end 
end 

账户控制器#INDEX

def index 
    #show user details 
    raise if not current_user 
    render json: { :user => current_user.as_json(:except=>[:created_at, :updated_at, :authorization_token, :provider, :uid, :id])} 
    rescue 
    render nothing: true, status: 403 
end 

我不断收到

1)Api::V1::AccountsController GET index with account has a 200 status code 
expected: 200 
got: 403 

有关我在哪里做错的任何想法吗?

UPDATE

module ControllerMacros 
    def login_user 
    before(:each) do 
     @request.env["devise.mapping"] = Devise.mappings[:user] 
     user = FactoryGirl.create(:user) 
     sign_in :user, user 
    end 
    end 
end 
+0

尝试用开始块包装提高。所以开始......举起......渲染json:{:user ... rescue render nothing:true,status:403 end –

+0

这个包装也不起作用... –

回答

0

更简单地实施

class SomeController < ApplicationController 

    before_action :authenticate 
    skip_before_action :verify_authenticity_token, if: :json_request? 

    def index 
    render json: { user: current_user... 
    end 

protected 
    def json_request? 
    request.format.json? 
    end 

    def authenticate 
    head :unauthorized unless current_user 
    end 
end 

我还建议在使用串行加载ActiveModel https://github.com/rails-api/active_model_serializers。这将分离呈现json和oy的逻辑将在序列化器下有一个单独的类,该序列化器定义了json输出。所以,你的渲染方法是这样的:

render json: current_user, status: :ok 

应用程序/串行器/ user.rb

class UserSerializer < ActiveModel::Serializer 
    attribute :id, :email #list your attributes for json output 
end 

如果你想测试你的rspec的JSON响应什么,我觉得最好的是对JSON模式类似测试这个库https://github.com/sharethrough/json-schema-rspec

希望它有帮助

+0

谢谢你的重构,我不知道这样写就可能......但这并不能回答我所要求的。错误仍然存​​在 –

+0

您是否在您的rspec中包含了devise助手? RSpec.configure do | config | config.include Devise :: TestHelpers,:type =>:控制器 结束 –

+0

是包含 –