[Rspec] Efficiently Speed Rspec test

參考第一篇文章

author has deleted
https://medium.com/the-code-review/5-rspec-tips-to-speed-up-testing-ruby-on-rails-projects-db8759a20869

Conclusion
前面 1 ~ 4 點,學習一些技巧和寫法,但是效能提升没特別提到
但文章的第 5 點 Efficiently load data records 得到几个方向

  1. Use let, rather than let!
  2. One is to use before_all instead of before_each in a test file
  3. Another is to have a global variables file, which loads an instance of each record before all tests start
  4. Another approach is to user FactoryBot’s build_stubbed method

參考第二篇文章

http://breazeal.com/blog/jasmineBefore.html
https://stackoverflow.com/questions/16617052/rails-rspec-before-all-vs-before-each

Conclusion

Always we write this for each example

1
2
3
before(:each) do
....
end

Maybe can use this to do only 1 query and 1 times insert to DB

1
2
3
before(:all) do
.....
end

參考第三篇文章

https://engineers.sg/video/speeding-up-your-test-suite-reddotrubyconf-2016--808
from ruby conference

影片

Conclusion

Absolutely point to 5 steps to save time
7 examples from 22 sec down to 3 sec

Can use Zeus or Spring to save time.
Yesterday which I read also mention this:

http://www.betterspecs.org/zh_tw/#spork

5 steps to follow:

(1) Measure test performance often and efficiently (now only 15 sec)
use Zeus | Spring, Rspec profile

(2) Avoid forceful database clean after each test (now only 7 sec, compare before save 47%)

bad:

1
2
3
4
5
6
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end

good:

1
2
3
4
5
6
config.before(:all) do
DatabaseCleaner.start
end
config.after(:all) do
DatabaseCleaner.clean
end

(3) Declare and reuse associations (now only 5 sec, compare before save 40%)

1
2
3
before(:all) do
@user = FactoryGirl.create(:user)
end

Reuse in object declaration

1
2
3
4
5
6
7
before(:each) do
@order_fulfillment = FactoryGirl.create(
:order_fulfillment,
user: @user,
order: @order,
shoper:@user
end

(4) Use build stubbed, until you can’t (now only 4.8 sec, compare before save 4%)
FactoryGirl’s build strategied

  1. create
  2. build
  3. build stubbed
1
2
3
4
5
6
7
before(:each) do
@order_fulfillment = FactoryGirl.build_stubbed(
:order_fulfillment,
user: @user,
order: @order,
shoper:@user
end

(5) Use mocks and stubs to imitate slow operations (now only 3 sec, compare before save 38%)

1
2
3
4
5
6
7
8
before do
allow(FeatureToggles::GeeTest).
to receive(:disabled?).
and_return(false)
allow_any_instance_of(Captcha::GeeTest).
to receive(:validate!).
and_raise(Captcha::GeeTest::Error.new("Captcha Validation Failed"))
end

Ref others

https://chaione.com/blog/increase-performance-rspec-tests/

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×