RSpec - 存根



如果您已阅读 RSpec Doubles(又称 Mocks)部分,那么您就已了解 RSpec Stubs。在 RSpec 中,一个存根通常称为方法存根,这是一种特殊的方法类型,可“替代”现有方法或尚未存在的方法。

以下是 RSpec Doubles 部分中的代码 −

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')

让我们采用上述代码并使用旧的 RSpec 语法替换这两行 allow()

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() 语法,但我们在此处提供了较旧的样式,以便您在看到时能够识别它。

广告