Optimising Rspec Tests to Avoid Repeating Complex Setup Proceedures

久未见 提交于 2019-12-25 04:56:07

问题


So here's my problem:

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 doesn't currently support an around(:all) hook however. Any ideas?


回答1:


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



来源:https://stackoverflow.com/questions/12646871/optimising-rspec-tests-to-avoid-repeating-complex-setup-proceedures

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!