Rails 7.2测试中Google Drive凭证Fixture配置报错排查
问题场景与报错
我在开发Ruby on Rails 7.2(Ruby 3.3.3)应用,该应用集成Google Drive API。为了避免测试时触发OAuth2流程,我想把Google Drive凭证存入fixtures,但不想把敏感凭证提交到版本控制。
模型代码:
class Drive < ApplicationRecord validates :name, presence: true validates :provider, inclusion: { in: %w[google_drive, dropbox] } encrypts :credentials end
我的fixtures配置:
# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html one: name: MyDrive provider: google_drive credentials: <%= Rails.application.credentials.google_drive_credentials %>
直接在fixtures里写JSON格式的凭证能正常运行,但会把敏感信息提交到版本控制,这是我不想看到的:
credentials: "{\"client_id\":\"xxxxx\",\"access_token\":\"xxxxx\",\"refresh_token\":\"xxxxx\",\"scope\":[\"https://www.googleapis.com/auth/drive.metadata.readonly\"],\"expiration_time_millis\":1722059441000}"
运行测试时触发以下错误:
Error: PullFilesMetadataJobTest#test_job_is_called: MultiJson::ParseError: unexpected token at '{"client_id":"xxxxx", "access_token":"xxxxx", "refresh_token":"xxxxx", "scope":["https://www.googleapis.com/auth/drive.metadata.readonly"], "expiration_time_millis":1722059441000}'
解决方法
方法1:确保凭证在credentials中是标准JSON字符串
如果config/credentials/test.yml.enc里的google_drive_credentials是Ruby哈希格式,插入fixtures后会生成非标准的Ruby哈希字符串(比如带=>符号),导致MultiJson解析失败。
修改test.yml.enc,把凭证存为JSON字符串:
google_drive_credentials: '{"client_id":"xxxxx","access_token":"xxxxx","refresh_token":"xxxxx","scope":["https://www.googleapis.com/auth/drive.metadata.readonly"],"expiration_time_millis":1722059441000}'
方法2:在fixtures中把Ruby哈希转为JSON字符串
如果credentials里存的是Ruby哈希,直接在fixtures中调用to_json方法转换为标准JSON:
one: name: MyDrive provider: google_drive credentials: <%= Rails.application.credentials.google_drive_credentials.to_json %>
这样输出的就是符合要求的JSON字符串,MultiJson可以正常解析。
方法3:确认加密字段的测试环境配置
因为模型使用了encrypts :credentials,要确保测试环境的加密功能正常启用(config.active_record.encryption.enabled默认是true)。如果加密配置异常,也可能导致解密后的凭证格式错误,触发解析失败。
内容的提问来源于stack exchange,提问作者Ghassen Rjab
相关产品推荐
相关产品推荐

