RSpec - 模拟对象

RSpec - 模拟对象 首页 / RSpec入门教程 / RSpec - 模拟对象

在本章中,无涯教程将讨论RSpec Doubles,RSpec Double是一个模拟对象,在代码中模拟系统的另一个对象,方便测试。

假设您为学校构建一个应用程序,有一个教室,还有一个学生。类定义如下:

无涯教程网

class ClassRoom 
   def initialize(students) 
      @students=students 
   end 
   
   def list_student_names 
      @students.map(&:name).join(',') 
   end 
end

这是一个简单的类,它具有一个方法list_student_names,该方法返回以逗号分隔的学生姓名。现在,想为此教室能创建测试,但是如果还没有创建Student类,该怎么做呢?这时需要测试Double。

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

来源:LearnFk无涯教程网

list_student_names方法在其@students成员变量中的每个Student对象上调用name方法。因此,需要一个Double来实现name方法。

这是ClassRoom的代码以及RSpec示例,但请注意,没有定义Student类-

class ClassRoom 
   def initialize(students) 
      @students=students 
   end
   
   def list_student_names 
      @students.map(&:name).join(',') 
   end 
end

describe ClassRoom do 
   it 'the list_student_names method should work correctly' do 
      student1=double('student') 
      student2=double('student') 
      
      allow(student1).to receive(:name) { 'John Smith'} 
      allow(student2).to receive(:name) { 'Jill Smith'} 
      
      cr=ClassRoom.new [student1,student2]
      expect(cr.list_student_names).to eq('John Smith,Jill Smith') 
   end 
end

执行以上代码后,将产生以下输出。

. 
Finished in 0.01 seconds (files took 0.11201 seconds to load) 
1 example, 0 failures

如您所见,使用 test double 允许您测试代码,即使该代码依赖于未定义或不可用的类。

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

技术教程推荐

TensorFlow快速入门与实战 -〔彭靖田〕

深入拆解Tomcat & Jetty -〔李号双〕

Serverless入门课 -〔蒲松洋(秦粤)〕

用户体验设计实战课 -〔相辉〕

手把手带你搭建秒杀系统 -〔佘志东〕

Tony Bai · Go语言第一课 -〔Tony Bai〕

徐昊 · TDD项目实战70讲 -〔徐昊〕

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

超级访谈:对话毕玄 -〔毕玄〕

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