📜  RSpec-挂钩

📅  最后修改于: 2020-12-06 10:56:40             🧑  作者: Mango


在编写单元测试时,通常可以在测试之前和之后运行设置和拆卸代码。设置代码是用于配置或“设置”测试条件的代码。拆解代码进行清理,以确保环境处于一致状态以进行后续测试。

一般来说,您的测试应相互独立。当您运行一整套测试并且其中一个失败时,您要确信它失败是因为所测试的代码存在错误,而不是因为先前的测试使环境处于不一致状态。

RSpec中最常用的挂钩是在挂钩之前和之后。它们提供了一种定义和运行我们上面讨论的设置和拆卸代码的方法。让我们考虑这个示例代码-

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

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

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方法要在示例组中的每个示例之前运行,即,上面代码中describe块中的两个示例块。

在以下行中:@simple_class = SimpleClass.new,我们正在创建SimpleClass类的新实例,并将其分配给对象的实例变量。您可能想知道什么对象? RSpec在describe块范围内在幕后创建一个特殊类。这允许您将值分配给此类的实例变量,您可以在示例中的it块内访问这些值。这也使得在我们的测试中编写更简洁的代码变得容易。如果每个测试(示例)都需要一个SimpleClass实例,则可以将该代码放在before钩子中,而不必将其添加到每个示例中。

注意,“创建SimpleClass类的新实例”这一行被写入控制台两次,这表明在每个it块中调用钩子之前。

正如我们已经提到的,RSpec还具有一个after钩子,并且before和after钩子都可以采用:all作为参数。 after挂钩将在指定目标之后运行。 :all目标表示该挂钩将在所有示例之前/之后运行。这是一个简单的示例,说明何时调用每个挂钩。

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