Fixing Rails deployment errors with Capistrano

After upgrading a Rails web application from Rails 4.2 to Rails 5.0 and attempting to deploy it using Capistrano, I got stuck on “Your Ruby version is 1.9.3, but your Gemfile specified 2.3.1” errors that gave me quite a headache – but the solution is really simple.

I manage Ruby versions with rbenv and deploy my Rails app with Capistrano to an Apache server with Phusion Passenger.

Capistrano issues the following command over SSH:

cd /var/mysite/releases/20160828151409 &&
( export RBENV_ROOT="/home/daniel/.rbenv" RBENV_VERSION="2.3.1" ;
RBENV_ROOT=/home/daniel/.rbenv RBENV_VERSION=2.3.1
/home/daniel/.rbenv/bin/rbenv exec bundle install
--path /var/mysite/shared/bundle --without development test
--deployment --quiet )

The key to the problem lies in the use of

rbenv exec bundle install

During the Rails 5 upgrade, a bin/bundle stub was created in my Rails application directory. This was detected by rbenv exec and given priority over the Ruby version-specific bundle. Therefore, rather than using the bundle command in the rbenv environment, this stub loaded the system-wide bundle, which of course runs on the system-wide Ruby 1.9.3 (provided by Ubuntu 14.04.3 LTS Server):

#!/usr/bin/env ruby
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
load Gem.bin_path('bundler', 'bundle')

I removed the bin/bundle stub, and the deployment worked without problems.

Initially I had thought that maybe the rbenv environment was not loaded properly when commands were executed over SSH, but that was not the problem.

Note to self: When upgrading Ruby (rather than Rails), do not forget to adjust the Ruby version number in config/deploy.rb:

# config/deploy.rb
set :rbenv_ruby, '2.3.1'

And also make sure the web server knows the right version number. Here’s the setup for Apache 2 with Phusion Passenger:

# /etc/apache2/sites-available/mysite.conf
PassengerRuby /home/daniel/.rbenv/versions/2.3.1/bin/ruby