优化 Rspec 测试以避免重复复杂的设置过程

编程入门 行业动态 更新时间:2024-10-21 07:27:59
本文介绍了优化 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 测试以避免重复复杂的设置过程

本文发布于:2023-11-10 22:12:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1576602.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:过程   测试   以避免   Rspec

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!