第 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交互。

Method: FactoryBot::Syntax::Methods#attributes_for

#attributes_for(name, *traits_and_overrides, &block) ⇒ Hash

根据factories中的注册的name, 生成一个hash属性。

  describe '#create' do
    context "as an authenticated user" do
      before do
        @user = FactoryGirl.create(:user)
      end
      it "adds a project" do
        project_params = FactoryGirl.attributes_for(:project)
        sign_in @user
        expect {
          post :create, params: {project: project_params }
        }.to change(@user.projects, :count).by(1)

#expect(@user.projects.count).to eq(1)  #替代方法

      end
    end

change()方法,by()方法,是哪里定义的?

在gem rspec-expectations 中定义的。

This class is part of a private API. 文档提示:私有类,尽量避免使用.

https://www.rubydoc.info/gems/rspec-expectations/RSpec/Matchers:change

  describe '#update' do
    context 'as an authorized user' do
      before do
        @user = FactoryGirl.create(:user)
        @project = FactoryGirl.create(:project, owner: @user)
      end
      it "updates a project" do
        project_params = FactoryGirl.attributes_for(:project, name: "New Project Name")
        sign_in @user
        patch :update, params: {id: @project.id, project: project_params}

#已经更新数据库,但内存里@project实例变量没有更新,所以要reload.

        @project.reload
        expect(@project.name).to eq "New Project Name"
      end
    end
  end

reload()方法 从数据库中根据接收者的primary-key id调取record并更新接收者的属性。

Reloading is commonly used in test suites to test something is actually written to the database, or when some action modifies the corresponding row in the database but not the object in memory:

经常用于测试,测试记录实际已写入数据库,或者测试当一些action在数据库中修改了相关记录但在内存中已存在这个对象变量是否更新。

5.4 测试用户输入导致的错误

    context "with invalid attributes" do
      before do
        @user = FactoryGirl.create(:user)
      end
      it "does not add a project" do
        project_params = FactoryGirl.attributes_for(:project, :invalid)
        sign_in @user
        post :create, params: {project: project_params}
        expect(@user.projects.count).to eq(0)
        # expect {
        #   post :create, params: { project: project_params }
        # }.to_not change(@user.projects, :count)
      end
    end

这里用到trait,在projects.rb的中定义的一个trait

trait :invalid do

name nil

end

⚠️ trait 和 factory继承的区别,一个是增加特点,用的时候需要和预构件一起用;一个是完全继承父类属性并增加自己的特色,是一个新的预构件。

5.5

处理非 HTML 输出 ,如何编写对JSON格式的测试。

bin/rails g rspec:controller
tasks

spec/controllers/tasks_controller_spec.rb 测试控制器show动作

RSpec.describe TasksController, type: :controller do
  before do
    @user = FactoryGirl.create(:user)
    @project = FactoryGirl.create(:project, owner:@user)
    @task = @project.tasks.create!(name: "Test task")
  end
  describe '#show' do
    it "responds with JSON formatted output" do
      sign_in @user
      get :show, format: :json,
        params:{project_id: @project.id, id: @task.id}
      expect(response.content_type).to eq "application/json"
    end
  end
end
通过format: :json格式,控制器处理相应的请求,返回application/json类型的内容。

content_type方法属于 ActionDispatch::Response类的实例方法。

5.6小结

控制器测试,测试的是user登陆和未登陆状态下,已经不同用户权限下,对action 是否成功的测试。

在实际测试中,控制器测试已经不流行了。

Rspec: everyday-rspec实操。5:controller test(了解基础)的更多相关文章

  1. Rspec: everyday-rspec实操。FactoryBot预构件 (rspec-expectations gem 查看匹配器) 1-4章

    总文档连接: RSpec.info/documentation/ 包括core, expectiation,rails , mock, 点击最新版本,然后右上角搜索class, method. 第3章 ...

  2. Istio的流量管理(实操二)(istio 系列四)

    Istio的流量管理(实操二)(istio 系列四) 涵盖官方文档Traffic Management章节中的inrgess部分. 目录 Istio的流量管理(实操二)(istio 系列四) Ingr ...

  3. ABP入门系列(1)——学习Abp框架之实操演练

    作为.Net工地搬砖长工一名,一直致力于挖坑(Bug)填坑(Debug),但技术却不见长进.也曾热情于新技术的学习,憧憬过成为技术大拿.从前端到后端,从bootstrap到javascript,从py ...

  4. 号外号外:9月13号《Speed-BI云平台案例实操--十分钟做报表》开讲了

    引言:如何快速分析纷繁复杂的数据?如何快速做出老板满意的报表?如何快速将Speed-BI云平台运用到实际场景中?         本课程将通过各行各业案例背景,将Speed-BI云平台运用到实际场景中 ...

  5. Mysql MHA(GTID)配置(实操)

    实现环境 centos6.7 MYSQL5.6.36 主:192.168.1.191 从1:192.168.1.145 从2:192.168.1.146 监测:放在从2上 192.168.1.146 ...

  6. Selenium之unittest测试框架详谈及实操

    申明:本文是基于python3.x及selenium3.x. unittest,也可以称为PyUnit,可以用来创建全面的测试套件,可以用于单元自动化测试(模块).功能自动化测试(UI)等等. 官方文 ...

  7. unittest测试框架详谈及实操(二)

    类级别的setUp()方法与tearDown()方法 在实操(一)的例子中,通过setUp()方法为每个测试方法都创建了一个Chrome实例,并且在每个测试方法执行结束后要关闭实例.是不是觉得有个多余 ...

  8. .net基础学java系列(四)Console实操

    上一篇文章 .net基础学java系列(三)徘徊反思 本章节没啥营养,请绕路! 看视频,不实操,对于上了年龄的人来说,是记不住的!我已经看了几遍IDEA的教学视频: https://edu.51cto ...

  9. RTN 实操

    创建房间 test-rtn 10001 e2uii6r7r 8LfwOcreM76OiV1V1y8jXrMG_BNa-cmktpWUznRa:kdYdsEpcYLc5ceWEHPaK0ZDI7Qc=: ...

  10. 6.3 Pandora 实操 - 数据立方

    简介 数据立方是适用于大规模实时数据(每天百亿条,10TB+ 级别数据)查询与分析的数据库系统,提供交互式的访问数据的能力,支持数据过滤.分组.聚合,实现亚秒级以内对亿行级别的数据表进行多维探索分析. ...

随机推荐

  1. python写一个密码生成器的类,要求有个类变量,统计一下一共生成过多少个密码。 要求有4个方法,1:构造方法 2 实例方法 3 类方法 4 静态方法

    生成指定长度的随机数字密码 生成指定长度的随机字母密码 生成指定长度的随机数字和字母的混合 #encoding=utf-8   import random import string class pa ...

  2. Linux服务器配置---安装telnet

    安装telnet      telnet是标准的远程登录协议,历史悠久.但是telnet的对话数据没有加密,甚至用户名和密码都是明文显示,这样的服务风险极大.目前大多数系统多已经不会再安装这个服务了, ...

  3. P3868 [TJOI2009]猜数字

    [TJOI2009]猜数字 中国剩余定理 求解i=1 to n : x≡a[i] (mod b[i])的同余方程组 设 t= ∏i=1 to n b[i] 我们先求出 i=1 to n : x≡1 ( ...

  4. SACD ISO镜像中提取DSDIFF(DFF)、DSF文件

                      听语音 | 浏览:5620 | 更新:2015-08-25 11:46 | 标签:硬件 1 2 3 4 5 分步阅读 现在有一种比较流行的无损音乐传输介质是SACD ...

  5. 02: DOM 实例

    1.1 Event 对象 <body> <a id="myAnchor" href="http://www.microsoft.com"> ...

  6. 03: 自定义异步非阻塞tornado框架

    目录:Tornado其他篇 01: tornado基础篇 02: tornado进阶篇 03: 自定义异步非阻塞tornado框架 04: 打开tornado源码剖析处理过程 目录: 1.1 源码 1 ...

  7. 思考卷积神经网络(CNN)中各种意义

    原文:https://blog.csdn.net/aimreant/article/details/53145063 思考卷积神经网络(CNN)中各种意义 只是知道CNN是不够,我们需要对其进行解剖, ...

  8. mpvue小程序开发入门级指南

    报错指南 "Error: ERR_GET_SESSION_KEY {"code":5100,"message":"(-1)服务内部错误,请稍 ...

  9. 利用RNN(lstm)生成文本【转】

    本文转载自:https://www.jianshu.com/p/1a4f7f5b05ae 致谢以及参考 最近在做序列化标注项目,试着理解rnn的设计结构以及tensorflow中的具体实现方法.在知乎 ...

  10. uboot启动提示Error, wrong i2c adapter 0 max 0 possible后卡住了怎么办

    答:这个与i2c驱动有关,应该使能i2c驱动相关的配置项