2016-08-04 29 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

相关问题