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

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

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

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

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

技术教程推荐

左耳听风 -〔陈皓〕

技术管理实战36讲 -〔刘建国〕

性能测试实战30讲 -〔高楼〕

接口测试入门课 -〔陈磊〕

后端存储实战课 -〔李玥〕

图解 Google V8 -〔李兵〕

编程高手必学的内存知识 -〔海纳〕

eBPF核心技术与实战 -〔倪朋飞〕

超级访谈:对话道哥 -〔吴翰清(道哥)〕

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