Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Rails Testing: Tips for lightning fast test suites

Rails Testing: Tips for lightning fast test suites

Have you been taking a lot more coffee breaks lately while you wait for your tests to run? Is it so bad you don’t feel like writing specs for your app anymore? In this talk, I share a few strategies we used to reduce our build time by almost 75% on one of our Ruby on Rails application.

Avatar for Raoul DIFFOUO

Raoul DIFFOUO

February 06, 2020
Tweet

Other Decks in Programming

Transcript

  1. Rails Testing Tips for lightning⚡ fast test suites Raoul Diffouo

    Software Engineer Prodigy Finance @diraulo
  2. Split config files • spec_helper.rb contains bare minimum config to

    run test suites. Keep this file as slim as possible and only add config required by all type of specs • rails_helper.rb contains rails specific config. This will be used for specs that require rails to be loaded. This includes controller, features, system & models specs.
  3. What’s a Transaction? “A transaction, in the context of a

    database, is a logical unit that is independently executed for data retrieval or updates. In relational databases, database transactions must be atomic, consistent, isolated and durable -- summarized as the ACID acronym.” https://www.techopedia.com/definition/16455/transaction
  4. Cleaning DB with Transaction (cont.) • advantage It’s faster •

    gotchas - Whatever you create before your tests will remain in the DB - Watch out for specs that are dependent on table IDs. The count won’t reset in between specs - Issues when the test involves multiple DB connections
  5. Cleaning DB with truncation (cont.) • pro(s) - Completely wipes

    out your DB in between specs - Helps when you have tests that depend on multiple DB connections • con(s) - It’s very slow
  6. You might not need DatabaseCleaner • Rails Transactional Fixtures (Tests)

    - Have nothing to do with Fixtures - Behave like the transaction strategy of DatabaseCleaner config.use_transactional_fixtures = true • Rails 5.1+ now has better support for multiple DB connections
  7. factories: You’re probably using them wrong ☹ • create(:course) returns

    a model instance and saves it to the DB • build(:course) returns a model instance that has not been saved to the DB • build_stubbed(:course) Like build, returns an unsaved model object. Unlike build, it assigns a fake ActiveRecord ID to the model and stubs out db-interaction methods (like save) Source: Rails 5 Testing Prescriptions
  8. Wrap-up • Prefer Transactions over Truncation • Avoid excessive calls

    to the DB • Only create data you need • Don’t use DB Migrations to seed DBs
  9. • http://betterspecs.org • Rails 5 Test Prescriptions • Effective Testing

    with RSpec 3 • https://github.com/Datab aseCleaner/database_clea ner • https://anti-pattern.com /transactional-fixtures- in-rails