ปัญหาการใช้ SimpleCov สำหรับ Test Coverage บน Rails6
**Technical Alert
พอดีว่ากำลังกลับมา Setup ตัว Code Coverage Report ใน Rails6 ปรากฎว่าเจอปัญหา ว่าเหมือน Coverage ได้ 0% ตลอดเลย ทั้งๆ ที่คิดว่าไม่น่าจะตั้งผิด เลยไปคุ้ยๆ หน่อย พบปัญหาว่า
ใน Rails6 มันมีการ Parallelize ซึ่งอาจจะทำให้การจัดการ ระบบเพี้ยนๆ
require ‘simplecov’
ENV[‘RAILS_ENV’] ||= ‘test’
require_relative ‘../config/environment’
require ‘rails/test_help’class ActiveSupport::TestCase
# Run tests in parallel with specified workers
parallelize(workers: :number_of_processors)
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
# Add more helper methods to be used by all tests here…
end
จริงๆ แล้ว Parallel Test มันช่วยให้การเทสจะทำงานให้เร็วขึ้น อย่างไรก็ตามมันก็เป็นไปได้ ที่ฟังก์ชั่นใหม่ๆ จะไปกระทบกับอะไรบางอย่าง ซึ่งในที่นี้คือ simplecov
ซึ่งจากที่ไปค้นดู ก็พบวิธีแก้ปัญหาในเบื้องต้น อยู่ 2 แบบ
แบบแรกคือการ disable parallelize ซะ ซึ่งก็ไม่ใช่อย่างที่ต้องการสักเท่าไหร่
ส่วนอีกวิธีก็คือ การไปสั่ง ให้ Simplecov สร้าง result ในจังหวะ Teardown ของ Parallelize โดยใส่เพิ่มใน Code เดิม ดังนี้
require ‘simplecov’
ENV[‘RAILS_ENV’] ||= ‘test’
require_relative ‘../config/environment’
require ‘rails/test_help’class ActiveSupport::TestCase
# Run tests in parallel with specified workers
parallelize(workers: :number_of_processors)
if ENV['COVERAGE']
parallelize_setup do |worker|
SimpleCov.command_name "#{SimpleCov.command_name}-#{worker}"
end parallelize_teardown do |worker|
SimpleCov.result
end
end # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
# Add more helper methods to be used by all tests here…
end
ตรงนี้ก็สามารถจะทำให้ Coverage กลับมาที่ต้องการได้
ว่าแล้วก็กลับไปเขียน Test ต่อไป…