RSpec - 存根

如果你已经阅读过关于RSpec Doubles(又名Mocks)的部分,那么你已经看过RSpec Stubs了.在RSpec中,存根通常被称为方法存根,它是一种特殊类型的方法,它"代表"现有方法,或者一种甚至不存在的方法.

以下是RSpec Doubles&minus部分的代码;

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


在我们的示例中,allow()方法提供了测试ClassRoom类所需的方法存根.在这种情况下,我们需要一个像Student类的实例一样的对象,但该类实际上并不存在(尚未).我们知道Student类需要提供一个name()方法,我们使用allow()为name()创建一个方法存根.

需要注意的一点是,RSpec的语法多年来有所改变.在RSpec的旧版本中,上面的方法存根将被定义为这样 :

student1.stub(:name).and_return('John Smith') 
student2.stub(:name).and_return('Jill Smith')


让我们拿上面的代码并替换两个 allow()使用旧RSpec语法的行 :

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')
      
      student1.stub(:name).and_return('John Smith')
      student2.stub(:name).and_return('Jill Smith') 
      
      cr = ClassRoom.new [student1,student2] 
      expect(cr.list_student_names).to eq('John Smith,Jill Smith') 
   end 
end


执行上述代码时,您将看到此输出 :

.
Deprecation Warnings:

Using `stub` from rspec-mocks' old `:should` syntax without explicitly 
   enabling the syntax is deprec 

ated. Use the new `:expect` syntax or explicitly enable `:should` instead. 
   Called from C:/rspec_tuto 

rial/spec/double_spec.rb:15:in `block (2 levels) in <top (required)>'.
If you need more of the backtrace for any of these deprecations 
   to identify where to make the necessary changes, you can configure 

`config.raise_errors_for_deprecations!`, and it will turn the 
   deprecation warnings into errors, giving you the full backtrace.

1 deprecation warning total

Finished in 0.002 seconds (files took 0.11401 seconds to load)
1 example, 0 failures


当您需要在RSpec示例中创建方法存根时,建议您使用新的allow()语法,但我们在这里提供了较旧的样式,以便您在看到它时能够识别它它