在本章中,我们将讨论RSpec Test Doubles,也称为RSpec Mocks. Double是一个可以"站在"另一个对象的对象.您可能想知道这究竟意味着什么,以及为什么需要一个.
假设您正在为学校建立一个应用程序,并且您有一个代表学生教室的课程和另一个对于学生来说,就是你有一个课堂课和一个学生课.你需要首先编写其中一个类的代码,所以我们说,从Classroom类开始减去;
class ClassRoom def initialize(students) @students = students end def list_student_names @students.map(&:name).join(',') end end
这是一个简单的类,它有一个方法list_student_names,它返回逗号分隔的学生名字串.现在,我们想为这个类创建测试,但是如果我们还没有创建Student类,我们该怎么做呢?我们需要一个测试Double.
此外,如果我们有一个"虚拟"类,其行为类似于Student对象,那么我们的ClassRoom测试将不依赖于Student类.我们将此测试称为隔离.
如果我们的ClassRoom测试不依赖于任何其他类,那么当测试失败时,我们可以立即知道我们的ClassRoom类中存在错误不是其他一些课.请记住,在现实世界中,您可能正在构建一个需要与其他人编写的类交互的类.
这是RSpec Doubles(模拟)变得有用的地方.我们的list_student_names方法在其@students成员变量中的每个Student对象上调用name方法.因此,我们需要一个实现名称方法的Double.
以下是ClassRoom的代码以及RSpec示例(测试),但请注意没有定义Student类和减去;
class ClassRoom def initialize(students) @students = students end def list_student_names @students.map(&:name).join(',') end enddescribe 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
当上述公司de执行,它将产生以下输出.您的计算机上的经过时间可能略有不同,减去;
. Finished in 0.01 seconds (files took 0.11201 seconds to load) 1 example, 0 failures
如你所见,使用一个 test double 允许您测试代码,即使它依赖于未定义或不可用的类.此外,这意味着当测试失败时,您可以立即告诉您这是因为您班级中的问题,而不是其他人写的课程.