Bundler is what makes "it works on my machine" mean "it works on every machine". Used well, it gives a Rails team reproducible installs and calm upgrades. Used carelessly, it produces sprawling version pins and surprise breakages.
Commit the lockfile
For applications, always commit Gemfile.lock. It records the exact versions that were tested, so production, CI and every developer run the same code. (Library gems are different, but a Rails app is an application.)
Constrain versions sensibly
gem "rails", "~> 7.1.0" # allow patch releases only
gem "sidekiq", "~> 7.2" # allow minor releases within 7.x
gem "nokogiri" # trust the lockfile
gem "some_fragile_gem", "1.4.2" # exact pin, with a comment saying why
- The pessimistic operator
~>is the usual choice for gems with a reliable versioning history. - Leave most gems unconstrained and let the lockfile hold the exact version.
- If you must pin exactly, explain why in a comment so the pin can be removed later.
Updating without drama
- Update one gem at a time:
bundle update --conservative sidekiqchanges only that gem and the minimum of its dependencies. - Read the changelog for anything beyond a patch release.
- Run the full test suite before merging.
- Avoid a bare
bundle updateon a large app. It changes everything at once and makes failures hard to trace.
Running commands
Use bundle exec, or the binstubs in bin/, so commands use the bundled versions:
bin/rails db:migrate
bundle exec rspec
bundle exec rubocop
In CI
- Install with frozen settings (
bundle config set frozen true) so a Gemfile change without an updated lockfile fails the build. - Cache installed gems between runs, keyed on the lockfile contents.
- Run
bundle auditor an equivalent to flag gems with known vulnerabilities. - Exclude groups that production does not need with
bundle config set without "development test".