Rails 5.2用户测试报错:BCrypt未初始化及加载失败求助
Hey there, let's work through this BCrypt issue you're hitting. It's super confusing when the app works in the browser but breaks in tests and the console—let's break down the fixes step by step:
1. Check Your Gemfile First
The most common culprit here is that bcrypt is only included in the production group in your Gemfile, meaning it's not loaded in test/development environments. Open your Gemfile and make sure the bcrypt line isn't nested inside a group :production do block. It should look like this:
gem 'bcrypt', '~> 3.1.7' # Use a version compatible with Rails 5.2; 3.1.x works great
2. Reinstall Dependencies & Clear Spring Cache
After updating the Gemfile, run these commands to make sure bcrypt is properly installed across all environments:
bundle install spring stop # Clears Rails' preloaded environment cache
Spring can sometimes hold onto old gem configurations, so stopping it ensures you're starting fresh.
3. Fix Your Fixtures
The error in users.yml happens because the fixture rendering context doesn't have BCrypt loaded by default (even if the gem is installed). You have two options here:
Option A: Pre-generate the Password Digest
Instead of using ERB to generate the digest in the fixture, create it once outside and paste the result. Here's how:
- Create a tiny Ruby script (e.g.,
generate_digest.rb) with this code:require 'bcrypt' puts BCrypt::Password.create('secret') - Run it with
ruby generate_digest.rb—it'll output a long encrypted string like$2a$12$... - Paste that string directly into your
users.yml:test_user: name: test_user password_digest: "$2a$12$..." # Replace with your generated string
Option B: Load BCrypt in Test Helper
If you prefer keeping the ERB in fixtures, add this line at the top of test/test_helper.rb:
require 'bcrypt'
This ensures BCrypt is available when fixtures are rendered.
4. Use Bundle Exec for Console & Tests
Always run your console and tests with bundle exec to ensure you're using the exact gems specified in your Gemfile:
bundle exec rails console # For testing BCrypt commands bundle exec rails test # To run your user tests
Skipping bundle exec might cause Rails to use system gems instead of your project's bundled ones, leading to missing dependencies.
Why Does the Browser Work?
Chances are your development environment was loading bcrypt correctly (maybe you installed it manually before), but the test environment wasn't. Or if you were testing in production mode, bcrypt is included there—but test/development need explicit setup.
Give these steps a try, and your tests and console should start working with BCrypt as expected!
内容的提问来源于stack exchange,提问作者Marko Avlijaš

