RSpec - Subjects主题

RSpec - Subjects主题 首页 / RSpec入门教程 / RSpec - Subjects主题

RSpec subjets 提供了编写简写测试用例的快捷方式。

考虑以下代码-

无涯教程网

class Person 
   attr_reader :first_name, :last_name 
   
   def initialize(first_name, last_name) 
      @first_name=first_name 
      @last_name=last_name 
   end 
end 

describe Person do 
   it 'create a new person with a first and last name' do
      person=Person.new 'John', 'Smith'
      
      expect(person).to have_attributes(first_name: 'John') 
      expect(person).to have_attributes(last_name: 'Smith') 
   end 
end

实际上实际上很清楚,但是无涯教程可以使用RSpec的主题函数来减少示例中的代码量。通过将人员对象实例化到describe行中来实现。

class Person 
   attr_reader :first_name, :last_name 
   
   def initialize(first_name, last_name) 
      @first_name=first_name 
      @last_name=last_name 
   end 
	
end 

describe Person.new 'John', 'Smith' do 
   it { is_expected.to have_attributes(first_name: 'John') } 
   it { is_expected.to have_attributes(last_name: 'Smith') }
end

运行此代码时,您将看到此输出-

链接:https://www.learnfk.comhttps://www.learnfk.com/rspec/rspec-subjects.html

来源:LearnFk无涯教程网

.. 
Finished in 0.003 seconds (files took 0.11201 seconds to load) 
2 examples, 0 failures

注意,第二个代码示例要简单得多。无涯教程在第一个示例中使用了一个 it块,并用两个 it块替换了它,最终它们需要更少的代码并且非常清楚。

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

程序员进阶攻略 -〔胡峰〕

白话法律42讲 -〔周甲徳〕

玩转Spring全家桶 -〔丁雪丰〕

Flutter核心技术与实战 -〔陈航〕

研发效率破局之道 -〔葛俊〕

摄影入门课 -〔小麥〕

Django快速开发实战 -〔吕召刚〕

人人都用得上的写作课 -〔涵柏〕

Go 语言项目开发实战 -〔孔令飞〕

好记忆不如烂笔头。留下您的足迹吧 :)