2016-08-04 40 views
2

我來到這個控制器規範沒有通過任何行動。對我來說很明顯,它不是測試任何東西。但對response.status == 200的期望不會失敗。所以我想了解Rspec如何構建控制器測試以及是否有默認的response.status == 200當沒有操作通過時,Rspec控制器測試是否有默認響應?

describe 'SomeController', type: :controller do 
    let!(:user){ FactoryGirl.create :admin_user } 
    before { sign_in user } 

    describe 'GET#action' do 
    it 'response is success' do 
     expect(response.status).to eq 200 
    end 
end 
end 




Finished in 0.93954 seconds (files took 1.63 seconds to load) 
1 example, 0 failures 

回答

2

作爲RSpec controller spec documents point out

控制器規範是一個RSpec包裝爲Rails功能測試 (ActionController::TestCase::Behavior)。

所以,在看的在碼文檔ActionController::TestCase::Behavior,下Special Instance Variables section,我們可以看到,ActionController::TestCase將自動提供a @response instance variablereadable as just response in the test),它是「一種ActionDispatch::TestResponse對象,表示最後一個HTTP的響應響應」。所以,這似乎解釋了爲什麼有一個response可以訪問,而無需在控制器規範中做出明確的請求,但爲什麼它的狀態爲200

恩,ActionDispatch::TestResponse繼承自ActionDispatch::Response,其中when initialized provides 200 as the default status。你甚至可以在你的Rails控制檯測試了這一點:

> ActionDispatch::TestResponse.new 
=> #<ActionDispatch::TestResponse:0x007fc449789b68 
@blank=false, 
@cache_control={}, 
@charset=nil, 
@committed=false, 
@content_type=nil, 
@cv= 
    #<MonitorMixin::ConditionVariable:0x007fc449789848 
    @cond=#<Thread::ConditionVariable:0x007fc449789820>, 
    @monitor=#<ActionDispatch::TestResponse:0x007fc449789b68 ...>>, 
@etag=nil, 
@header={"X-Frame-Options"=>"SAMEORIGIN", "X-XSS-Protection"=>"1; mode=block", "X-Content-Type-Options"=>"nosniff"}, 
@mon_count=0, 
@mon_mutex=#<Thread::Mutex:0x007fc449789a50>, 
@mon_owner=nil, 
@sending=false, 
@sending_file=false, 
@sent=false, 
@status=200, # <<< Here's your default status. 
@stream=#<ActionDispatch::Response::Buffer:0x007fc449789938 @buf=[], @closed=false, @response=#<ActionDispatch::TestResponse:0x007fc449789b68 ...>>> 

所以,我希望你在RSpec的控制器規格的response對象的理解,協助該深潛,因爲它肯定沒有地雷。

+0

偉大的答案保羅。這正是我期待的!謝謝 – vinibol12

相關問題