Rspec: everyday-rspec实操。5:controller test(了解基础)

Posted Mr-chen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Rspec: everyday-rspec实操。5:controller test(了解基础)相关的知识,希望对你有一定的参考价值。

5 章 控制器测试 

 

5.1基础

rails generate rspec:controller home 

 

RSpec.describe HomeController, type: :controller do
  describe ‘#index‘ do
    it "responds successfully" do
      get :index
      expect(response).to be_success
      # response 对象包含应用返回给浏览器的所有数据,包括 HTTP 响应码。

      # be_success 检查响应的状态是成 功(200 响应)还是失败(例如 500 异常)。

      expect(response).to have_http_status "200" 

    end
  end
end

be_success匹配器 ,have_http_status()匹配器

 

 

5.2要验证身份的controller test

 

如果程序有Devise。测试的时候,需要身份验证,则使用Devise Test helpers

Devise includes some test helpers for controller and integration tests. In order to use them, you need to include the repective module in you test cases/specs. 

包含一个测试模块.

class PostsControllerTest < ActionController::TestCase
include Devise::Test::ControllerHelpers
end
class PostsTests < ActionDispatch::IntegrationTest
include Devise::Test::IntegrationHelpers
end
RSpec.configure do |config|
config.include Devise::Test::IntegrationHelpers, type: :feature
 config.include Devise::Test::ControllerHelpers, type: :controller
 config.include Devise::Test::ControllerHelpers, type: :view
end

然后就可以使用sign_in, sign_out方法了

 

redirect_to 匹配器 

以下测试都是get的测试。

ProjectsController
  #inde
    as an authenticated user
      responds successfully
      returns a 200 response
    as a guest
      returns a 302 response

 

      redirects to the sign_in page

 

  #show

 

    as an authorized user
      responds successfully
    as an unauthorized user
      redirects to the dashboard

 

5.3 测试用户输入。

HTTP GET外,还有POST, PATCH, DELETE与controller交互。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

以上是关于Rspec: everyday-rspec实操。5:controller test(了解基础)的主要内容,如果未能解决你的问题,请参考以下文章

Rspec: everyday-rspec实操: 第10章测试其他功能,第11章TDD

Rails 5,Rspec:架构中未找到环境数据

5-13 Rspec实际(笔记)

Rails 教程 - Ch. 5 更漂亮的测试 Rspec

Circle CI 上的 Rspec 测试失败(Ruby on Rails 5.2.3)

比较相等的字符串时,RSpec 期望失败