Does "vanilla" Ruby dotenv pick up any file other than .env? - ruby

I want to use environment-specific variables in my non-Rails Ruby application.
I tried different file names like .env.test.local, .env.local, .env.test
I tried using the Dotenv.load and require 'dotenv/load' approaches
This is how I wrap the task
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
This is my server
require 'dotenv/load'
require 'sinatra'
require 'sinatra/reloader' if development?
set :bind, '0.0.0.0'
get ENV['API_URL'] do
'Hello World!'
end
My .env.test file
API_URL=/api/v1
Expected behavior
The API_URL variable should be available to the code run by the :test task (using bundle exec rake test).
Observed behavior
An error caused because ENV['API_URL'] is null.
/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
See the repo

I came up with this workaround
require 'dotenv'
require 'sinatra'
require 'sinatra/reloader' if development?
Dotenv.load(".env.#{ENV['APP_ENV']}") # Remember to set your app environment
set :bind, '0.0.0.0'
get ENV['API_URL'] do
'Hello World!'
end
It only works for .env.<ENVIROMENT> files. Maybe this could be wrapped in a function but I definitely would like this to be handled by the gem as in Rails applications, it makes more sense to me.

Related

How to load environment variables to ruby app spec using Rspec and .env

I'm currently working on writing tests for a Ruby class. The class makes use of environment variables.
When I run the spec with rspec spec/box_api.rb I get the following error:
Failures:
1) BoxApi#client success Create Boxr::Client object
Failure/Error: subject { BoxApi.new }
KeyError:
key not found: "BOX_USER_ID"
# ./src/clients/box_api.rb:8:in `fetch'
# ./src/clients/box_api.rb:8:in `initialize'
# ./spec/box_api.rb:14:in `block (4 levels) in <top (required)>'
It's not reading the environment variable.
I tried creating the .env.test.local file within spec folder without success. I'm using dotenv gem:
# Manage environment with .env file
gem 'dotenv', '~> 2.1.1'
How can I go about using the environment variables in test?
Instead of using dotenv for this, you could stub ENV keys in your tests:
describe Foo do
before do
allow(ENV).to receive(:[]).with('BOX_ID').and_return("1234")
end
it 'flips the environment variable value' do
expect(subject.flip).to eq '4321'
end
end
Or even stub the whole ENV:
describe Foo do
let(:env) do
{ 'BOX_ID' => '1234' }
end
before do
stub_const("ENV", env)
end
it 'flips the environment variable value' do
expect(subject.flip).to eq '4321'
end
end
I find this more reliable and easier to maintain than a separate file.
In your test helper file, you can add:
require 'dotenv'
Dotenv.load('.env.test.local')
This is on the dotenv readme

Top Required Error in Ruby Cucumber - Unable to execute the code

I have written a small piece of code just for launch a browser but I'm getting this error:
C:/Users/KASTURIPARIDA/RubymineProjects/Project1/features/support/driversettings.rb:6:in
<top (required)>'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/cucumber-1.3.17/bin/cucumber:13:in
' C:/Ruby193/bin/cucumber:23:in load'
C:/Ruby193/bin/cucumber:23:in'
-e:1:in `load'
Here below are all the code:
Support:
require 'rubygems'
require 'watir-webdriver'
Selenium::WebDriver::Chrome::Service.executable_path = 'C:\Ruby193\bin\chromedriver.exe'
$driver=watir::Browser.new :Chrome
wait 5
Feature:
Feature: Application
Scenario: Login to Open
And I have account with Opencart and launch page
Step definition:
And(/^I have account with Opencart and launch page$/) do
puts "browser loading"
$driver.goto("https://www.facebook.com/")
end
Try this:
Support
require 'rubygems'
require 'watir'
Selenium::WebDriver::Chrome.driver_path = 'C:\Ruby193\bin\chromedriver.exe'
$driver = Watir::Browser.new('chrome')
Hope it helps.

rake aborted after tests run & (intentionally) fail, before error messages are printed

I am running through the TestFirst tutorial and can't get past the first challenge due to some troubles with Rake (and rspec in general).
The tests I am trying to run:
require 'hello'
describe "the hello function" do
it "says hello" do
hello.should == "Hello!"
end
end
describe "the greet function" do
it "says hello to someone" do
greet("Alice").should == "Hello, Alice!"
end
it "says hello to someone else" do
greet("Bob").should == "Hello, Bob!"
end
end
I've only gotten so far as to create the hello.rb file (according to the tutorial) and adding
def hello
end
For the record, before I created the file, I got the long output saying that the require "hello" wasn't working, as expected, and upon creating the file that went away. So that all worked fine.
When I run the rake command, my output is (the bolded part is my main concern):
wendy#wendy-EL1352:~/the_odin_project/learn_ruby/00_hello$ rake
(in /home/wendy/the_odin_project/learn_ruby)
the hello function
says hello (FAILED - 1)
Failures:
1) the hello function says hello
Failure/Error: hello.should == "Hello!"
expected: "Hello!"
got: nil (using ==)
# ./00_hello/hello_spec.rb:120:in `block (2 levels) in '
Deprecation Warnings:
Using should from rspec-expectations' old :should syntax without explicitly enabling >the syntax is deprecated. Use the new :expect syntax or explicitly enable :should >instead. Called from /home/wendy/the_odin_project/learn_ruby/00_hello/hello_spec.rb:120:in >`block (2 levels) in '.
If you need more of the backtrace for any of these deprecations to
identify where to make the necessary changes, you can configure
config.raise_errors_for_deprecations!, and it will turn the
deprecation warnings into errors, giving you the full backtrace.
1 deprecation warning total
Finished in 0.00334 seconds (files took 0.14558 seconds to load)
1 example, 1 failure
Failed examples:
rspec ./00_hello/hello_spec.rb:119 # the hello function says hello
rake aborted!
/home/wendy/.rvm/rubies/ruby-2.0.0-p481/bin/ruby -S rspec /home/wendy/the_odin_project/learn_ruby/00_hello/hello_spec.rb -I/home/wendy/the_odin_project/learn_ruby/00_hello -I/home/wendy/the_odin_project/learn_ruby/00_hello/solution -f documentation -r ./rspec_config failed
/home/wendy/.rvm/gems/ruby-2.0.0-p481#railstutorial_rails_4_0/gems/rspec-core-2.13.1/lib/rspec/core/rake_task.rb:156:in run_task'
/home/wendy/.rvm/gems/ruby-2.0.0-p481#railstutorial_rails_4_0/gems/rspec-core-2.13.1/lib/rspec/core/rake_task.rb:124:inblock (2 levels) in initialize'
/home/wendy/.rvm/gems/ruby-2.0.0-p481#railstutorial_rails_4_0/gems/rspec-core-2.13.1/lib/rspec/core/rake_task.rb:122:in `block in initialize'
Tasks: TOP => default => spec
(See full trace by running task with --trace)
I'm not hugely concerned with the deprecation warning (I've looked through enough to be reasonably certain these aren't related). Although if you think that's the cause I'll bow my head in shame. I do need to figure out how to either rewrite the specs or change the config settings, but I have faith that I can do that myself. My real concern here is that Rake has access to the tests and can run them, but aborts before showing the error messages.
If I run rspec hello_spec.rb the output is here:
wendy#wendy-EL1352:~/the_odin_project/learn_ruby/00_hello$ rspec hello_spec.rb
/home/wendy/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in require': cannot load such file -- hello (LoadError)
from /home/wendy/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:inrequire'
from /home/wendy/the_odin_project/learn_ruby/00_hello/hello_spec.rb:116:in <top (required)>'
from /home/wendy/.rvm/gems/ruby-2.0.0-p481#railstutorial_rails_4_0/gems/rspec-core-3.0.2/lib/rspec/core/configuration.rb:1057:inload'
from /home/wendy/.rvm/gems/ruby-2.0.0-p481#railstutorial_rails_4_0/gems/rspec-core-3.0.2/lib/rspec/core/configuration.rb:1057:in block in load_spec_files'
from /home/wendy/.rvm/gems/ruby-2.0.0-p481#railstutorial_rails_4_0/gems/rspec-core-3.0.2/lib/rspec/core/configuration.rb:1057:ineach'
from /home/wendy/.rvm/gems/ruby-2.0.0-p481#railstutorial_rails_4_0/gems/rspec-core-3.0.2/lib/rspec/core/configuration.rb:1057:in load_spec_files'
from /home/wendy/.rvm/gems/ruby-2.0.0-p481#railstutorial_rails_4_0/gems/rspec-core-3.0.2/lib/rspec/core/runner.rb:97:insetup'
from /home/wendy/.rvm/gems/ruby-2.0.0-p481#railstutorial_rails_4_0/gems/rspec-core-3.0.2/lib/rspec/core/runner.rb:85:in run'
from /home/wendy/.rvm/gems/ruby-2.0.0-p481#railstutorial_rails_4_0/gems/rspec-core-3.0.2/lib/rspec/core/runner.rb:70:inrun'
from /home/wendy/.rvm/gems/ruby-2.0.0-p481#railstutorial_rails_4_0/gems/rspec-core-3.0.2/lib/rspec/core/runner.rb:38:in invoke'
from /home/wendy/.rvm/gems/ruby-2.0.0-p481#railstutorial_rails_4_0/gems/rspec-core-3.0.2/exe/rspec:4:in'
from /home/wendy/.rvm/gems/ruby-2.0.0-p481#railstutorial_rails_4_0/bin/rspec:23:in load'
from /home/wendy/.rvm/gems/ruby-2.0.0-p481#railstutorial_rails_4_0/bin/rspec:23:in'
So I'm kind of wondering why running rake has no problem linking the required hello.rb file but the rspec command doesn't. I just want to get these tests to run (and fail) properly so I can get on with the task.
The rakefile:
# This Rakefile has all the right settings to run the tests inside each lab
gem 'rspec', '~>2'
require 'rspec/core/rake_task'
task :default => :spec
desc "run tests for this lab"
RSpec::Core::RakeTask.new do |task|
lab = Rake.application.original_dir
task.pattern = "#{lab}/*_spec.rb"
task.rspec_opts = [ "-I#{lab}", "-I#{lab}/solution", '-f documentation', '-r ./rspec_config']
task.verbose = false
end
Adding gem 'ruby gems' does nothing but add more confusion to the outputs.
I have initialized rspec with rspec --init in previous attempts at this, both in the 00_hello directory as well as in the learn_ruby directory. In this case, I run into exactly the same error messages.
I've been going at learning Ruby and Rails for the past few months. Once or twice I've almost asked a question here, but I've ended up finding my answer halfway through drafting it. I am not having that kind of luck this time. I am truly stumped. Please help.
Thank you.
Edit with more info on rspec --init and use of 'spec_helper'
in the 00_hello folder, rspec --init and then including the spec_helper in the hello_spec.rb (as shown above - I included require 'spec_helper' below the require 'hello') produces the following error when run with the rake command:
wendy#wendy-EL1352:~/the_odin_project/learn_ruby/00_hello$ rake (in
/home/wendy/the_odin_project/learn_ruby)
/home/wendy/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in
`require': cannot load such file -- spec_helper (LoadError)
In the learn_ruby directory, I get the same output as above, where the tests run well enough to fail, but then I see rake abort! before the errors are listed and the same error as before:
the hello function says hello (FAILED - 1)
Failures:
1) the hello function says hello
Failure/Error: hello.should == "Hello!"
NameError:
undefined local variable or method hello' for #<RSpec::ExampleGroups::TheHelloFunction:0x00000002989278>
# ./00_hello/hello_spec.rb:122:inblock (2 levels) in '
Finished in 0.00094 seconds (files took 0.16985 seconds to load) 1
example, 1 failure
Failed examples:
rspec ./00_hello/hello_spec.rb:121 # the hello function says hello
rake aborted! /home/wendy/.rvm/rubies/ruby-2.0.0-p481/bin/ruby -S
rspec /home/wendy/the_odin_project/learn_ruby/00_hello/hello_spec.rb
-I/home/wendy/the_odin_project/learn_ruby/00_hello -I/home/wendy/the_odin_project/learn_ruby/00_hello/solution -f documentation -r ./rspec_config failed
(the reason the test failure is different is because I've gone back to just having the hello.rb file created without inserting the class name into the file - the tests are half running, but the rake aborted! won't go away)
This guy:
-I/home/wendy/the_odin_project/learn_ruby/00_hello/solution -f documentation -r ./rspec_config failed
can be found in the Rakefile:
RSpec::Core::RakeTask.new do |task|
lab = Rake.application.original_dir
task.pattern = "#{lab}/*_spec.rb"
**task.rspec_opts = [ "-I#{lab}", "-I#{lab}/solution", '-f documentation', '-r ./rspec_config']**
task.verbose = false
end
But I do not have enough understanding of Rake to even parse apart Google search results for problems with that line, or find what search terms to use to find relevant information. :/

rspec Cannot load such file after working the first time

When running through the rspec course in codeschool I keep running into the same problem. I will set up as requested and after creating zombie_spec.rb and running rspec I get the proper output listed below:
Justins-MacBook-Pro:rubyproject Justin$ rspec spec/lib/zombie_spec.rb
Run options: include {:focus=>true}
All examples were filtered out; ignoring {:focus=>true}
*
Pending:
A Zombie is named Ash
# Not yet implemented
# ./spec/lib/zombie_spec.rb:3
Finished in 0.00929 seconds
1 example, 0 failures, 1 pending
Randomized with seed 7259
As I continue on with the first video and create the class Zombie as mentioned I receive this error when running rspec again:
Justins-MacBook-Pro:rubyproject Justin$ rspec spec/lib/zombie_spec.rb
/usr/local/rvm/rubies/ruby-1.9.3-p392/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot load such file -- zombie (LoadError)
from /usr/local/rvm/rubies/ruby-1.9.3-p392/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from /Users/Justin/rubyproject/spec/lib/zombie_spec.rb:2:in `<top (required)>'
from /usr/local/rvm/gems/ruby-1.9.3-p392/gems/rspec-core-2.13.1/lib/rspec/core/configuration.rb:819:in `load'
from /usr/local/rvm/gems/ruby-1.9.3-p392/gems/rspec-core-2.13.1/lib/rspec/core/configuration.rb:819:in `block in load_spec_files'
from /usr/local/rvm/gems/ruby-1.9.3-p392/gems/rspec-core-2.13.1/lib/rspec/core/configuration.rb:819:in `each'
from /usr/local/rvm/gems/ruby-1.9.3-p392/gems/rspec-core-2.13.1/lib/rspec/core/configuration.rb:819:in `load_spec_files'
from /usr/local/rvm/gems/ruby-1.9.3-p392/gems/rspec-core-2.13.1/lib/rspec/core/command_line.rb:22:in `run'
from /usr/local/rvm/gems/ruby-1.9.3-p392/gems/rspec-core-2.13.1/lib/rspec/core/runner.rb:80:in `run'
from /usr/local/rvm/gems/ruby-1.9.3-p392/gems/rspec-core-2.13.1/lib/rspec/core/runner.rb:17:in `block in autorun'
After this I removed everything and uninstalled and reinstalled rspec. Retried it again and returned the same results.
Any clue what is going on?
Thank you in advance for your help!
require_relative will load the file from the same directory as the rspec file
I had pretty much the same issue, though mine never worked even once at first. Updating the zombie_spec.rb file to show the full path of my zombie.rb file seemed to get it working properly.
Eg:require "/home/me/ruby/spec/lib/zombie"
I use this and it worked
require_relative "zombie.rb"
Well if this still a problem I got into the same issue so I created a folder under spec/lib where I put all the codes and another spec/test where goes all the tests then it worked.
and I also added require_relative here is the code snippet
zombie_spec.rb
require 'spec_helper'
require_relative '../lib/zombie'
describe Zombie do
it "has a name called'Jack'" do
zb = Zombie.new
zb.name.should == "Jack"
end
it "has no brains" do
zb = Zombie.new
zb.should be_intelligent == false
end
end
zombie.rb
class Zombie
attr_accessor :name
def initialize
#name = "Jack"
end
def intelligent?
false
end
end

padrino && websockets

i'm looking for a way to open and use websockets from within a Padrino application. i know Padrino works with a single thread but i'm looking for a way to open websockets and share variables between its "onopen" "onclose" "onmessage" methods and Padrino controllers.
any idea how it's done ?
links i looked into:
Examples of Eventmachine usage with Padrino and Sinatra (only Sinatra worked for me)
em-websocket on GitHub
UPDATE 1:
this is my main.rb:
require 'rubygems' # <-- Added this require
require 'em-websocket'
require 'padrino-core'
require 'thin'
require File.expand_path("../config/boot.rb", __FILE__)
SOCKETS = []
EventMachine.run do # <-- Changed EM to EventMachine
# class App < Sinatra::Base
# get '/' do
# SOCKETS.each {|s| s.send "fooooo"}
# return "foo"
# end
# end
EventMachine::WebSocket.start(:host => '0.0.0.0', :port => 8080) do |ws| # <-- Added |ws|
# Websocket code here
ws.onopen {
ws.send "connected!!!!"
SOCKETS << ws
}
ws.onmessage { |msg|
puts "got message #{msg}"
ws.send "ECHO: #{msg}"
}
ws.onclose {
ws.send "WebSocket closed"
SOCKETS.delete ws
}
end
# You could also use Rainbows! instead of Thin.
# Any EM based Rack handler should do.
#App.run!({:port => 3000}) # <-- Changed this line from Thin.start to App.run!
Thin::Server.start Padrino.application, '0.0.0.0', 3000
end
i'm getting this exception:
/home/cstore/.rvm/gems/ruby-1.9.2-p290#runtime/gems/thin-1.2.11/lib/thin/daemonizing.rb:2:in `require': no such file to load -- daemons (LoadError)
from /home/cstore/.rvm/gems/ruby-1.9.2-p290#runtime/gems/thin-1.2.11/lib/thin/daemonizing.rb:2:in `<top (required)>'
from /home/cstore/.rvm/gems/ruby-1.9.2-p290#runtime/gems/thin-1.2.11/lib/thin/server.rb:50:in `<class:Server>'
from /home/cstore/.rvm/gems/ruby-1.9.2-p290#runtime/gems/thin-1.2.11/lib/thin/server.rb:48:in `<module:Thin>'
from /home/cstore/.rvm/gems/ruby-1.9.2-p290#runtime/gems/thin-1.2.11/lib/thin/server.rb:1:in `<top (required)>'
from main.rb:39:in `block in <main>'
from /home/cstore/.rvm/gems/ruby-1.9.2-p290#runtime/gems/eventmachine-0.12.10/lib/eventmachine.rb:256:in `call'
from /home/cstore/.rvm/gems/ruby-1.9.2-p290#runtime/gems/eventmachine-0.12.10/lib/eventmachine.rb:256:in `run_machine'
from /home/cstore/.rvm/gems/ruby-1.9.2-p290#runtime/gems/eventmachine-0.12.10/lib/eventmachine.rb:256:in `run'
from main.rb:9:in `<main>'
UPDATE 2:
Resolved thanks to Nathan !
I just added 'daemons' to Gemfile and reloaded my application.
Maybe you need to install daemons:
Edit your Gemfile:
# Adding this
gem 'daemons'
Install missing gems:
$ bundle install
What in particular from this example: https://github.com/igrigorik/em-websocket and Any success with Sinatra working together with EventMachine WebSockets? didn't work with Padrino but did with Sinatra? Can you explain the errors you got and why those examples failed (stacktraces)? Maybe we can help investigate.
I ran across this post and it helped me a bit, but I wanted to offer an alternative solution to anyone else who might stumble upon it. I chose to just directly modify the config.ru and mount a websocket-rack application.
Here's my config.ru where WSApp is a subclass of Rack::WebSocket::Application and is placed in the lib/ directory (therefore being automatically loaded by Padrino):
#!/usr/bin/env rackup
# encoding: utf-8
# This file can be used to start Padrino,
# just execute it from the command line.
require File.expand_path("../config/boot.rb", __FILE__)
# Setup routes
map '/' do
run Padrino.application
end
map '/ws' do
run WSApp.new
end
Since this is the top hit in Google right now, I'd like to link it to padrino-websockets, a clean DSL for writing websockets applications in Padrino.

Resources