我在 config/environment.rb 中定义了一个名为 LOCAL_SETTINGS 的常量,用于配置并在整个应用程序中使用。它是一个存储在 config/local_settings.yml
中的 YAML 文件,有时会包含 API key 等敏感数据。
我目前正在尝试为使用 LOCAL_SETTINGS["slack"]["slack_token"]
的方法编写规范。
问题是该常量没有按照我的期望进行 stub 。即 expect(subject.path).to eq(help_request)
失败,因为它返回包含非 stub LOCAL_SETTINGS
哈希的路径。
但是,如果我将调试器放在 stub_const
下,然后输入 LOCAL_SETTINGS
,我可以看到 Stub_const 已经起作用。
我的问题是:
- 我可以在 Rspec 中做些什么来让 stub 为
config/environment.rb
中定义的常量工作吗? - 我应该在其他地方简单地定义这个常量吗?如果是的话,在哪里?我需要在 app/lib/和 spec/文件夹中的整个应用程序中访问它。
我的config/environment.rb
文件:
# Load the Rails application.
require_relative 'application'
LOCAL_SETTINGS = YAML.load_file("#{Rails.root}/config/local_settings.yml")
# Initialize the Rails application.
Rails.application.initialize!
我的规范:
describe RequestBuilder, type: :model do
let(:help_params) { {"user_name"=>"some_user_name", "text"=>"release-bot help"} }
let(:help_builder) { RequestBuilder.new(help_params) }
let(:help_request) { "/api/files.upload?file=lib%2Fresponses%2Fhelp&filetype=ruby&channels=stubbed_channel&token=stubbed_token" }
let(:slack_settings) { {"slack"=>{"slack_token"=>"stubbed_token", "slack_channel"=>"stubbed_channel"}} }
context 'Given an incoming request' do
context 'With a correctly formatted request' do
context 'And the "help" command' do
subject { help_builder.build_request_hash }
it 'builds a request containing the help data' do
stub_const("LOCAL_SETTINGS", slack_settings)
expect(subject).to have_key(:request)
expect(subject[:request].path).to eq(help_request)
end
end
end
end
end
最佳答案
如果您使用的是 Rails,并且配置目录中已经有一个 .yaml
文件,我建议您查看 Rails custom configuration加载 YAML 文件。这样,您就能够将任何凭据与测试环境隔离,而无需为每个测试 stub LOCAL_SETTINGS
const 或更改任何类。
# config/local_settings.yml
development:
slack_token: some_dev_token
slack_channel: some_channel
test:
slack_token: fake_token
slack_channel: fake_channel
production:
slack_token: <%= ENV['SLACK_TOKEN'] %>
slack_channel: <%= ENV['SLACK_CHANNEL'] %>
然后加载这个配置文件:
# config/application.rb
module MyApp
class Application < Rails::Application
config.local_settings = config_for(:local_settings)
end
end
然后您可以从 Rails.configuration.local_settings['slack_token']
而不是从 LOCAL_SETTINGS
常量访问值。
关于ruby-on-rails - Rspec - 如何 stub config/environment.rb 中定义的常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44342527/