RSpecStubs
如果您已经阅读了RSpec Doubles部分,那么您已经看到了RSpec Stubs,它是一种特殊类型的方法,代表现有方法或尚不存在的方法。
这是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
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示例中创建方法Stubs时使用新的allow()语法。
祝学习愉快! (发现内容有误?请选中要编辑的内容 -> 右键 -> 修改 -> 提交!帮助我们改进教程质量)
精选教程推荐
👇 以下精选教程可能对您有帮助,拓展您的技术视野
暂无学习笔记,成为第一个分享的人吧!
您的笔记将帮助成千上万的学习者