Rspec - 如何存根在config / environment.rb中定义的常量?

时间:2017-06-03 09:38:16

标签: ruby-on-rails ruby rspec

我在config/environment.rb中定义了一个名为LOCAL_SETTINGS的常量,我在整个应用程序中用它来配置和使用。它是存储在config/local_settings.yml中的YAML文件,有时会包含API密钥等敏感数据。

我目前正在尝试为使用LOCAL_SETTINGS["slack"]["slack_token"]的方法编写规范。

问题是这个常数并没有被我的期望所困扰。即expect(subject.path).to eq(help_request)失败,因为它返回包含非存根LOCAL_SETTINGS哈希的路径。

但是,如果我将调试器放在stub_const下面然后键入LOCAL_SETTINGS,我可以看到stub_const已经有效。

我的问题是:

  1. 我可以在Rspec中做些什么来获取存根工作config/environment.rb中定义的常量?
  2. 我应该在其他地方简单地定义这个常量吗?如果是的话,在哪里?我需要在app / lib /和spec / folders中的应用程序中访问它。
  3. 我的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
    

1 个答案:

答案 0 :(得分:1)

如果您正在使用Rails,并且您已在config目录中有.yaml文件,我建议您查看Rails custom configuration以加载YAML文件。这样,您就可以从测试环境中隔离任何凭据,而无需为每个测试存根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常量中的值。

另一个blog post highlighting the custom configuration