2016-09-10 32 views
1

我已經重寫了默認的設計響應,它呈現json而不是html模板。當我用curl或postman測試它時,它工作正常,但是當它用rspec進行測試時。我已經閱讀了如何使用readme.md中的devise測試控制器的信息,以便它可以正常工作,但在我想測試未經身份驗證的請求時不起作用。設計重定向,而不是rspec中的json響應

響應接收到的:

<html><body>You are being <a href=\"http://test.host/users/sign_in\">redirected</a>.</body></html> 

代替:

{"error":"You need to sign in or sign up before continuing."} 

應用程序/控制器/ playlists_controller.rb:

class PlaylistsController < ApplicationController 
    before_action :authenticate_user! 

    def index 
    render json: Playlist.all 
    end 
end 

應用程序/控制器/ sessions_controller.rb:

class SessionsController < Devise::SessionsController 
    clear_respond_to 
    respond_to :json 
end 

規格/控制器/ playlists_controller_spec.rb:

require 'rails_helper' 

describe PlaylistsController do 
    context 'when user is not signed in' do 
    it 'returns authorization error message' do 
     get :index 
     expect(response.body).to eq 'some message here' 
    end 
    end 
end 

規格/支持/ devise.rb

RSpec.configure do |config| 
    config.include Devise::TestHelpers, type: :controller 
end 

回答

0

它不能在你的控制器測試中工作並且在curl中工作的原因是因爲你沒有碰到:index格式爲:json(您已將其邏輯寫入respond_to :json)。

更改此

it 'returns authorization error message' do 
    get :index 
    ... 
end 

這個

it 'returns authorization error message' do 
    get :index, format: :json 
    ... 
end 
+0

這工作。我想知道爲什麼這個工作沒有設置內容類型或接受標題和rspec不捲曲的捲曲... – Robs

+0

有趣。我假設你在curl中使用了內容類型json。我實際上不知道爲什麼它會使用沒有內容類型集的json – MilesStanfield

+0

實際上沒有設置標題。它應該默認響應json,因爲它應該被重寫控制器。無論如何 - 感謝回答我:) – Robs

0

您可以定義FailureApp或使用條件過濾器,無論是在回答建議類似的問題:https://stackoverflow.com/a/10042104/580346

+0

很好,這是爲測試添加額外的邏輯。我已經用curl工作了,但是這個測試失敗了。我不認爲我應該只爲測試更改應用程序代碼。 – Robs

+0

你是對的,我錯過了它與捲曲一起工作,並在測試中失敗。順便說一句,關於格式和標題,你可能會喜歡這篇文章:http://blog.iempire.ru/2016/09/05/rails-obstractions/ – mrzasa

1

在Rails 5,我能得到控制動作處理爲JSON是唯一的方法:

get :action, params: { format: :json, ... } 

希望這可以幫助 !