2016-06-13 69 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

是包含 –