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块替换了它,最终它们需要更少的代码并且非常清楚。

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

来源:LearnFk无涯教程网

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

技术教程推荐

从0开始学游戏开发 -〔蔡能〕

软件测试52讲 -〔茹炳晟〕

MongoDB高手课 -〔唐建法(TJ)〕

深度学习推荐系统实战 -〔王喆〕

大厂晋升指南 -〔李运华〕

如何读懂一首诗 -〔王天博〕

遗留系统现代化实战 -〔姚琪琳〕

高并发系统实战课 -〔徐长龙〕

结构沟通力 -〔李忠秋〕

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