在编写单元测试时,通常可以在测试之前和之后运行设置代码,方便初始化或清理数据。
RSpec中最常用的挂钩是before和after钩子,让无涯教程看看以下示例代码-
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钩子,并且before和after钩子都可以接受: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
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)