【问题标题】:Is there a default response for Rspec controller tests when no action is passed?没有通过任何操作时,Rspec 控制器测试是否有默认响应?
【发布时间】:2016-08-04 22:34:59
【问题描述】:

我遇到了这个控制器规范,它没有通过任何操作。我很清楚它没有测试任何东西。但是对response.status == 200 的期望并没有失败。所以我想了解 Rspec 如何构建控制器测试以及是否有默认的response.status == 200

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

【问题讨论】:

    标签: ruby-on-rails rspec


    【解决方案1】:

    作为RSpec controller spec documents point out

    控制器规范是 Rails 功能测试的 RSpec 包装器 (ActionController::TestCase::Behavior)。

    因此,查看ActionController::TestCase::Behavior 的代码内文档,在Special Instance Variables section 下,我们可以看到ActionController::TestCase 将自动提供a @response instance variable (readable as just response in the test),即“ActionDispatch::TestResponse对象,表示最后一个 HTTP 响应的响应”。所以,这似乎可以解释为什么有一个 response 可以在不需要控制器规范中的明确请求的情况下被访问,但为什么它的状态是 200

    嗯,ActionDispatch::TestResponse 继承自 ActionDispatch::Responsewhen 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 对象,就像我的一样。

    【讨论】:

    • 保罗的回答很好。这正是我想要的!谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    相关资源
    最近更新 更多