所以这是我的问题:
我正在为我的 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 endRSpec 目前不支持 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 测试以避免重复复杂的设置过程
发布评论