搭建Ruby+Capybara+Cucumber/Rspec环境时遇gem install bundler权限错误
Hey there, I totally get this frustration—system Ruby on Mac is notoriously finicky with permissions, since it lives in a root-owned directory. Let’s walk through the best ways to fix this, starting with the most sustainable solution first.
1. Use a Ruby Version Manager (Recommended Long-Term Fix)
The system Ruby that comes pre-installed on Mac is locked down for good reason—you don’t want to mess with it and break system tools that rely on it. Instead, use a version manager like rbenv or rvm to install Ruby in your user directory (where you have full permissions):
- First, if you don’t have Homebrew installed, grab it first (it’s a must-have for Mac dev tools):
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" - Install rbenv with Homebrew:
brew install rbenv - Initialize rbenv so it loads every time you open a terminal. Run this command and follow the prompt to add the required line to your shell config file (either
~/.zshrcfor newer Macs or~/.bash_profilefor older ones):rbenv init - Restart your terminal, then install your desired Ruby version (2.3.7 in your case):
rbenv install 2.3.7 - Set this Ruby version as your global default (or use
rbenv local 2.3.7in your project directory to set it per-project):rbenv global 2.3.7 - Now you can install Bundler without sudo (and no permission errors!):
gem install bundler
2. Install Gems to a User-Owned Directory (Quick Fix)
If you don’t want to use a version manager right now, you can configure Ruby to install gems in a directory you own:
- Create a user-specific gem directory:
mkdir -p ~/.gem/ruby/2.3.0 - Set the
GEM_HOMEenvironment variable to point to this directory. Add these lines to your shell config file (~/.zshrcor~/.bash_profile) so they persist across terminal sessions:export GEM_HOME=~/.gem/ruby/2.3.0 export PATH="$GEM_HOME/bin:$PATH" - Reload your shell config to apply the changes:
source ~/.zshrc # or source ~/.bash_profile - Now install Bundler normally:
gem install bundler
3. Modify System Gem Directory Permissions (Not Recommended)
I’m including this only as an emergency last resort—changing permissions on system directories can cause unexpected issues with macOS tools that depend on the system Ruby. If you still want to try it:
- Take ownership of the system gem directory:
sudo chown -R $(whoami) /Library/Ruby/Gems/2.3.0 - Then install Bundler:
gem install bundler
Why This Happens
The /Library/Ruby/Gems/2.3.0 directory is owned by root, so your regular user account doesn’t have write access. Using sudo to install gems here can lead to permission conflicts down the line (which is why you’re seeing this error now), so sticking with a version manager is the safest bet for long-term Ruby development.
内容的提问来源于stack exchange,提问作者drkvader

