我想在我的非 Rails Ruby 应用程序中使用特定于环境的变量。
我尝试了不同的文件名,如.env.test.local
, .env.local
,.env.test
我尝试使用Dotenv.load
andrequire 'dotenv/load'
方法
这就是我包装任务的方式
require 'rspec'
require 'rack/test'
require 'rspec/core/rake_task'
require 'dotenv/tasks'
task test: :dotenv do
RSpec::Core::RakeTask.new(:spec).run_task(verbose: true)
end
这是我的服务器
require 'dotenv/load'
require 'sinatra'
require 'sinatra/reloader' if development?
set :bind, '0.0.0.0'
get ENV['API_URL'] do
'Hello World!'
end
我的.env.test
档案
API_URL=/api/v1
预期行为
API_URL 变量应该可用于:test
任务运行的代码(使用bundle exec rake test
)。
观察到的行为
由于ENV['API_URL']
为空而导致的错误。
/Users/mariogil/.rvm/rubies/ruby-2.6.3/bin/ruby -I/Users/mariogil/.rvm/gems/ruby-2.6.3/gems/rspec-core-3.8.0/lib:/Users/mariogil/.rvm/gems/ruby-2.6.3/gems/rspec-support-3.8.0/lib /Users/mariogil/.rvm/gems/ruby-2.6.3/gems/rspec-core-3.8.0/exe/rspec --pattern spec/\*\*\{,/\*/\*\*\}/\*_spec.rb
An error occurred while loading ./spec/server_spec.rb.
Failure/Error:
get ENV['API_URL'] do
'Hello World!'
end
TypeError:
NilClass can't be coerced into Mustermann::Pattern
# /Users/mariogil/.rvm/gems/ruby-2.6.3/gems/mustermann-1.0.3/lib/mustermann.rb:73:in `new'
# /Users/mariogil/.rvm/gems/ruby-2.6.3/gems/sinatra-2.0.5/lib/sinatra/base.rb:1641:in `compile'
# /Users/mariogil/.rvm/gems/ruby-2.6.3/gems/sinatra-2.0.5/lib/sinatra/base.rb:1629:in `compile!'
# /Users/mariogil/.rvm/gems/ruby-2.6.3/gems/sinatra-2.0.5/lib/sinatra/base.rb:1604:in `route'
# /Users/mariogil/.rvm/gems/ruby-2.6.3/gems/sinatra-2.0.5/lib/sinatra/base.rb:1386:in `get'
# /Users/mariogil/.rvm/gems/ruby-2.6.3/gems/sinatra-2.0.5/lib/sinatra/base.rb:1925:in `block (2 levels) in delegate'
# ./lib/server.rb:9:in `<top (required)>'
# ./spec/server_spec.rb:6:in `require'
# ./spec/server_spec.rb:6:in `<top (required)>'
No examples found.
Finished in 0.00026 seconds (files took 0.18951 seconds to load)
0 examples, 0 failures, 1 error occurred outside of examples
/Users/mariogil/.rvm/rubies/ruby-2.6.3/bin/ruby -I/Users/mariogil/.rvm/gems/ruby-2.6.3/gems/rspec-core-3.8.0/lib:/Users/mariogil/.rvm/gems/ruby-2.6.3/gems/rspec-support-3.8.0/lib /Users/mariogil/.rvm/gems/ruby-2.6.3/gems/rspec-core-3.8.0/exe/rspec --pattern spec/\*\*\{,/\*/\*\*\}/\*_spec.rb failed