2017-06-03 64 views
2

我在config/environment.rb中定義了一個名爲LOCAL_SETTINGS的常量,我用它來配置和使用整個應用程序。這是一個YAML文件存儲在config/local_settings.yml,有時會包含敏感數據,如API鍵等Rspec - 如何存根在config/environment.rb中定義的常量?

我目前正在嘗試編寫一個使用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 /文件夾中的應用程序中訪問它。

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

如果您使用Rails和你已經有了一個.yaml文件config目錄下,我建議看在Rails custom configuration加載YAML文件。通過這種方式,您將能夠隔離測試環境中的任何憑據,而無需爲每個測試存儲常量,或更改任何類。

# 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