RSpec - Hooks勾子

RSpec - Hooks勾子 首页 / RSpec入门教程 / RSpec - Hooks勾子

在编写单元测试时,通常可以在测试之前和之后运行设置代码,方便初始化或清理数据。

RSpec中最常用的挂钩是beforeafter钩子,让无涯教程看看以下示例代码-

class SimpleClass 
   attr_accessor :message 
   
   def initialize() 
      puts "\nCreating a new instance of the SimpleClass class" 
      @message='howdy' 
   end 
   
   def update_message(new_message) 
      @message=new_message 
   end 
end 

describe SimpleClass do 
   before(:each) do 
      @simple_class=SimpleClass.new 
   end 
   
   it 'should have an initial message' do 
      expect(@simple_class).to_not be_nil
      @simple_class.message='Something else. . .' 
   end 
   
   it 'should be able to change its message' do
      @simple_class.update_message('a new message')
      expect(@simple_class.message).to_not be 'howdy' 
   end
end

运行此代码时,将获得以下输出-

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

来源:LearnFk无涯教程网

Creating a new instance of the SimpleClass class 
. 
Creating a new instance of the SimpleClass class 
. 
Finished in 0.003 seconds (files took 0.11401 seconds to load) 
2 examples, 0 failures

before(:each)方法是定义的钩子代码,当传递:each参数时,每个示例执行前都会调用before方法。

正如上面所提到的,RSpec还具有一个after钩子,并且beforeafter钩子都可以接受:all作为参数,after钩子将在之后运行, :all目标表示该钩子将在所有示例before/after运行。这是一个简单的示例,说明何时调用每个钩子。

describe "Before and after hooks" do 
   before(:each) do 
      puts "Runs before each Example" 
   end 
   
   after(:each) do 
      puts "Runs after each Example" 
   end 
   
   before(:all) do 
      puts "Runs before all Examples" 
   end 
   
   after(:all) do 
      puts "Runs after all Examples"
   end 
   
   it 'is the first Example in this spec file' do 
      puts 'Running the first Example' 
   end 
   
   it 'is the second Example in this spec file' do 
      puts 'Running the second Example' 
   end 
end

运行上面的代码时,您将看到此输出-

Runs before all Examples 
Runs before each Example 
Running the first Example 
Runs after each Example 
.Runs before each Example 
Running the second Example 
Runs after each Example 
.Runs after all Examples

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

技术教程推荐

数据分析实战45讲 -〔陈旸〕

Vue开发实战 -〔唐金州〕

苏杰的产品创新课 -〔苏杰〕

性能工程高手课 -〔庄振运〕

手把手带你写一门编程语言 -〔宫文学〕

人人都用得上的数字化思维课 -〔付晓岩〕

结构写作力 -〔李忠秋〕

给程序员的写作课 -〔高磊〕

云原生基础架构实战课 -〔潘野〕

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