优化 Rspec 测试以避免重复复杂的设置过程 [英] Optimising Rspec Tests to Avoid Repeating Complex Setup Proceedures

查看:41
本文介绍了优化 Rspec 测试以避免重复复杂的设置过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这是我的问题:

我正在为我的 Rails 模型编写单元测试,我有一整套示例,每个示例都需要相同的设置才能运行.如果我没记错的话,为多个 RSpec 测试设置相同方式的常用方法是使用 before(:each) 块,如下所示:

I am writing unit tests for my Rails models and I have a whole set of examples that each require the same setup in order to run. If I'm not mistaken, the usual way to set things up the same way for multiple RSpec tests is to use a before(:each) block, like this:

describe Model do
  before(:each) do
    # Complex setup
  end
  # Examples
end

不幸的是,需要此设置的示例集开始变得相当大,并且为每个测试完成这个复杂的设置过程需要很长时间.我试过这样做:

Unfortunately the set of examples which needs this setup is starting to get rather large, and completing this complex setup proceedure for each and every test takes a long time. I tried doing this:

describe Model do
  before(:all) do
    # Complex setup
  end
  # Examples
end

但是这种方法在我完成后并没有回滚我的设置,这会在以后的测试中导致问题.我真正想要的是做这样的事情:

But this method doesn't roll back my setup though after I'm done with it, which causes problems in later tests. What I really want is to do something like this:

describe Model do
  around(:all) do |examples|
    transaction do
      # Complex setup
      examples.run
      raise ActiveRecord::Rollback
    end
  end
  # Examples
end

RSpec 目前不支持 around(:all) 钩子.有什么想法吗?

RSpec doesn't currently support an around(:all) hook however. Any ideas?

推荐答案

最简单的方法是使用 after(:all) 块在测试后进行清理.

The easiest way to do this would just be to use an after(:all) block to clean up after your tests.

这篇关于优化 Rspec 测试以避免重复复杂的设置过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆