JimmyTsai
2 min readMar 28, 2019

[ Test ] Efficiently Speed Rspec test

Ref

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

REF

from ruby conf

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:

Measure test performance often and efficiently (now only 15 sec)

use Zeus | Spring, Rspec profile

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

bad:

config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end

good:

config.before(:all) do
DatabaseCleaner.start
end
config.after(:all) do
DatabaseCleaner.clean
end

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

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

Reuse in object declaration

before(:each) do
@order_fulfillment = FactoryGirl.create(
:order_fulfillment,
user: @user,
order: @order,
shoper:@user
end

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

before(:each) do
@order_fulfillment = FactoryGirl.build_stubbed(
:order_fulfillment,
user: @user,
order: @order,
shoper:@user
end

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

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

我部落格搬家囉!以後會在這發文:

https://blog.gmifly.tw/