为什么我的环境变量没有被看到 - rspec 3.1.0,rails engine 4.1.9

时间:2015-01-28 21:44:58

标签: ruby-on-rails ruby rspec environment-variables

我有以下测试文件,在before(:each)do ... end部分我正在使用一些环境变量,这些 - 因为我不知道spec是从dummy读取还是引擎config/它自己的放置在假人的config/application.yml和引擎根config/application.yml

require 'spec_helper'

describe Xaaron::UsersController, :type => :controller do
  routes { Xaaron::Engine.routes }

  context "publish created users" do
    before(:each) do
      Xaaron.configuration.reset
      no_user_member_roles_relation

      binding.pry
      Xaaron.configuration.publish_to_black_bird = true
      Xaaron.configuration.black_bird_api_url = ENV['BLACKBIRD_API_URL']
      Xaaron.configuration.black_bird_api_key = ENV['BLACKBIRD_API_KEY']

    end

    it "should publish to blackbird" do
      VCR.use_cassette 'publisher/create_user_response' do
        post :create, user: {
          first_name: 'sample', user_name: 'johnq',
          email: 'sample_sample_sample@sample.com', email_confirmation: 'sample_sample_sample@sample.com',
          password: 'SamplePassword', password_confirmation: 'SamplePassword'
        }

        expect(response).to redirect_to login_path
      end
    end
  end

end

现在因为这是本地主机测试,我不在乎我是否向您展示这些(两个应用都在localhost上):

两个位置的application.yml文件包含以下内容:

BLACKBIRD_API_KEY: d1cab0ac344f5074797b8c2b9ce90070e8af3405de8431fa17150a0f3420b41e
BLACKBIRD_API_URL: http://site.local.com::5000/api/internal/v1/

当测试运行时,它会失败,因为nil:NilClass,在这种方法中发生:

# We need to check if Blackbird is alive.
def is_alive?
  # Do a simple get and capture the response
  response = HTTParty.get(
    Xaaron.configuration.black_bird_api_url + 'alive/',
    :headers => { "HTTP_AUTHORIZATION" => Xaaron.configuration.black_bird_api_key }
  )

  # If the response is 200 return true, else reeturn thje response code
  if response.code == 200
    return true
  else
    return response.code
  end
end

确切的行是:

Xaaron.configuration.black_bird_api_url + 'alive/'

当我将binding.pry放在此行之上并执行Xaaron.configuration.black_bird_api_url时,我得到nil,所以当我ENV['BLACKBIRD_API_URL']时,我也得到nil

所以我的问题是:

为什么我的环境变量为nil,因为它们非常清晰。

1 个答案:

答案 0 :(得分:0)

除非您在调用Rails时从命令行指定环境变量,否则Rails默认情况下不会加载环境变量。您希望使用figarodotenv来加载文件中的环境变量。我相信你想要figaro,因为它是从application.yml而不是.env文件中读取的。