rake spec failed, it cannot load or find constant or global variable - ruby

I create standalone rspec test script to testing existing api framework. It works pretty well, but I found problem where in the Rakefile I need to assign some value from YAML file (uri link, email) either CONSTANT or $global_var the code in the Rakefile looks like this:
require 'rubygems'
require 'bundler/setup'
require 'yaml'
require 'rspec/core/rake_task'
task :default => :spec
desc 'Running rspec test'
task :spec, :option do |t, opt|
choice = opt[:choice]
if choice == "production"
puts 'Test running on production'
VAR = YAML::load(File.read(File.expand_path("../config/prod_variable.yml", __FILE__)))
elsif choice == "development"
puts 'Test running on development'
VAR = YAML::load(File.read(File.expand_path("../config/dev_variable.yml", __FILE__)))
end
puts VAR['URI'] #=> print out the value correctly
RSpec::Core::RakeTask.new do |task|
test = Rake.application.original_dir
task.fail_on_error = false
task.rspec_opts = '--format documentation --color'
end
end
When I run the rake command on the terminal, the rspec failed find the VAR constant value. Here is the error message from rspec
Failures:
1) ApiTest Testing API platform for GET request
Failure/Error: #var = ApiTest.new(VAR['URI'] ,
NameError:
uninitialized constant VAR
# ./rspec_test/api_test/api_test_get_spec.rb:8:in `block (2 levels) in <top (required)>'
2) ApiTest Testing API platform for POST request
Failure/Error: #zat = ApiTest.new(VAR['URI'] ,
NameError:
uninitialized constant VAR
# ./rspec_test/api_test/api_test_post_spec.rb:7:in `block (2 levels) in <top (required)>'
Is there any idea how to get this works? I need to get value from VAR constant or global variable, but seems ruby failed to assign the value.

If opt[:choice] is neither "production" nor "development", VAR is undefined in your code.

Related

Dependency Injection causing both Rspec failure and IRB failure

Note: I am a Ruby and programming novice.
I have a class called JourneyLog I am trying to get a method called start to instantiate a new instance of another class, called Journey
class JourneyLog
attr_reader :journey_class
def initialize(journey_class: Journey)
#journey_class = journey_class
#journeys = []
end
def start(station)
journey_class.new(entry_station: station)
end
end
When I go into irbi get the following issue
2.2.3 :001 > require './lib/journeylog'
=> true
2.2.3 :002 > journeylog = JourneyLog.new
NameError: uninitialized constant JourneyLog::Journey
from /Users/BartJudge/Desktop/Makers_2018/oystercard-challenge/lib/journeylog.rb:4:in `initialize'
from (irb):2:in `new'
from (irb):2
from /Users/BartJudge/.rvm/rubies/ruby-2.2.3/bin/irb:15:in `<main>'
2.2.3 :003 >
I also have the following Rspec test
require 'journeylog'
describe JourneyLog do
let(:journey) { double :journey, entry_station: nil, complete?: false, fare: 1}
let(:station) { double :station }
let(:journey_class) { double :journey_class, new: journey }
describe '#start' do
it 'starts a journey' do
expect(journey_class).to receive(:new).with(entry_station: station)
subject.start(station)
end
end
end
I get the following Rspec failure;
1) JourneyLog#start starts a journey
Failure/Error: expect(journey_class).to receive(:new).with(entry_station: station)
(Double :journey_class).new({:entry_station=>#<Double :station>})
expected: 1 time with arguments: ({:entry_station=>#<Double :station>})
received: 0 times
# ./spec/jorneylog_spec.rb:9:in `block (3 levels) in <top (required)>'
I am at a total loss on what the problem is, or where to look for some answers.
I'm assuming I'm not injecting the Journey class properly, but thats as far as I can get myself.
Could someone provide some assistance?
In the journeylog.rb file you need to load the Journey class:
require 'journey' # I guess the Journey class is defined in lib/journey.rb
In the spec file you need to pass journey_class to the JourneyLog constructor:
describe JourneyLog do
subject { described_class.new(journey_class: journey_class) }
# ...

Custom Rake task unable to be called twice in same Rakefile unike Rake::TestTask

I recently read an "older", 2009, article about how to make a Custom Rake tasks. So far it works for the first iteration, but I saw that Rake::TestTask can be called twice, so I figured I could do it, however my name attr_accessor is not picking up the symbol I'm passing to it.
require 'rake'
require 'rake/tasklib'
module Phil
class FooTask < Rake::TaskLib
attr_accessor :name
attr_accessor :data
attr_accessor :task_dependencies
def initialize(name = :task, task_dependencies)
#name = name
#data = nil
yield self if block_given?
#task_dependencies = task_dependencies
define
end
def define
desc "Run the #{#name} task"
task #name => #task_dependencies do
puts 'Some Test being Printed'
puts #data
sh 'echo blah'
end
self
end
end
end
Phil::FooTask.new :foo, [:call_me_first, :call_me_second]
task :call_me_first do
puts 'I am called first because I am a dependency'
end
task :call_me_second do
puts 'I am called second because Im also a dependency'
end
Phil::FooTask.new(:stuff) do |t|
t.data = 'I am a stuff task.'
end
The following is the results I get.
C:\Users\user01\Desktop
λ rake --tasks
rake foo # Run the foo task
rake stuff # Run the stuff task
C:\Users\user01\Desktop
λ rake foo
I am called first because I am a dependency
I am called second because Im also a dependency
Some Test being Printed
echo blah
blah
C:\Users\user01\Desktop
λ rake stuff --trace
** Invoke stuff (first_time)
rake aborted!
Don't know how to build task '{}' (see --tasks)
C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/task_manager.rb:58:in `[]'
C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:61:in `lookup_prerequisite'
C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:57:in `block in prerequisite_tasks'
C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:57:in `map'
C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:57:in `prerequisite_tasks'
C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:214:in `invoke_prerequisites'
C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:193:in `block in invoke_with_call_chain'
C:/tools/ruby23/lib/ruby/2.3.0/monitor.rb:214:in `mon_synchronize'
C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:187:in `invoke_with_call_chain'
C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/task.rb:180:in `invoke'
C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:152:in `invoke_task'
C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:108:in `block (2 levels) in top_level'
C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:108:in `each'
C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:108:in `block in top_level'
C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:117:in `run_with_threads'
C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:102:in `top_level'
C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:80:in `block in run'
C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:178:in `standard_exception_handling'
C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:77:in `run'
C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/rake-12.0.0/exe/rake:27:in `<top (required)>'
C:/tools/ruby23/bin/rake:22:in `load'
C:/tools/ruby23/bin/rake:22:in `<main>'
Tasks: TOP => stuff
I'm not sure why the Rake task is failing. Even from reading the Rake's TestTask code, it seems I'm doing mostly everything correctly. I'll also say that I'm not a professional on Ruby and all the little tricks.
Keep arguments with default value at the end in method declaration!
The reason rake stuff is raising error is because of your Phil::FooTask.new(:stuff) do |t| call. Your initialize method expects two arguments. The error is in your declaration of the constructor where you've declared name = :task which has a default value of :task. However, the second parameter task_dependencies is expected. It is the second parameter that you're missing when initializing task with name :stuff.
Modify your initialize method declaration as follows:
def initialize(name = :task, task_dependencies = [])
Then you should see correct tasks when invoking rake -T:
rake foo # Run the foo task
rake stuff # Run the stuff task

rspec-puppet tests fail undefined method

I'm trying to write my first rspec test for a simple puppet class. Here's the class, rspec test and results. I'm new to rspec and would like to know what I'm doing wrong here. I follow the directions here http://rspec-puppet.com/setup/ to configure rspec-puppet for these tests. Thanks.
Class example for cron module init.pp
class cron {
service { 'crond' :
ensure => running,
enable => true
}
}
Rspec Test
require '/etc/puppetlabs/puppet/modules/cron/spec/spec_helper'
describe 'cron', :type => :module do
it { should contain_class('cron') }
it do should contain_service('crond').with(
'ensure' => 'running',
'enable' => 'true'
) end
end
Results
FF
Failures:
1) cron
Failure/Error: it { should contain_class('cron') }
NoMethodError:
undefined method `contain_class' for #<RSpec::Core::ExampleGroup::Nested_1:0x00000001c66d70>
# ./cron_spec.rb:5:in `block (2 levels) in <top (required)>'
2) cron
Failure/Error: it do should contain_service('crond').with(
NoMethodError:
undefined method `contain_service' for #<RSpec::Core::ExampleGroup::Nested_1:0x00000001c867b0>
# ./cron_spec.rb:6:in `block (2 levels) in <top (required)>'
Finished in 0.00237 seconds
2 examples, 2 failures
Failed examples:
rspec ./cron_spec.rb:5 # cron
rspec ./cron_spec.rb:6 # cron
Where did you pick up the
describe 'cron', :type => :module
syntax? That may be obsolete.
With current versions of rspec-puppet, you describe
classes
defined types
functions
hosts
You basically just want to put your spec right into spec/classes/cron_spec.rb, that should do half your work for you, e.g.
# spec/classes/cron.rb
require "#{File.join(File.dirname(__FILE__),'..','spec_helper.rb')}"
describe 'cron' do
it { should contain_service('crond').with('ensure' => 'running') }
it { should contain_service('crond').with('enable' => 'true') }
end
It is good practice to have distinct tests for each attribute value, so that possible future regressions can be identified more accurately.
Do see the README.
For a nice example of a well structured module test-suite see example42's modules.

`block in non_options': file not found: (ArgumentError)

I'm trying to open browser url based on argument passed to script. Hence I wrote following ruby code:
require 'selenium-webdriver'
require 'test/unit'
class TestTitle < Test::Unit::TestCase
def setup
$driver = Selenium::WebDriver.for :firefox
if ARGV[0] == 'google'
$driver.get 'http://www.google.com'
elsif ARGV[0] == 'twitter'
$driver.get 'http://www.twitter.com'
end
end
def test_title
puts $driver.title
end
def teardown
$driver.quit
end
end
When I passed argument: ruby test.rb 'google', it results into following error:
c:/Ruby193/lib/ruby/1.9.1/test/unit.rb:167:in `block in non_options': file not found: google (ArgumentError)
from c:/Ruby193/lib/ruby/1.9.1/test/unit.rb:146:in `map!'
from c:/Ruby193/lib/ruby/1.9.1/test/unit.rb:146:in `non_options'
from c:/Ruby193/lib/ruby/1.9.1/test/unit.rb:207:in `non_options'
from c:/Ruby193/lib/ruby/1.9.1/test/unit.rb:52:in `process_args'
from c:/Ruby193/lib/ruby/1.9.1/minitest/unit.rb:891:in `_run'
from c:/Ruby193/lib/ruby/1.9.1/minitest/unit.rb:884:in `run'
from c:/Ruby193/lib/ruby/1.9.1/test/unit.rb:21:in `run'
from c:/Ruby193/lib/ruby/1.9.1/test/unit.rb:326:in `block (2 levels) in autorun'
from c:/Ruby193/lib/ruby/1.9.1/test/unit.rb:27:in `run_once'
from c:/Ruby193/lib/ruby/1.9.1/test/unit.rb:325:in `block in autorun'
Please help me understand what I'm doing wrong.
It appears that test-unit (as of 1.9.1) grabs command line options in its GlobOptions module. You are using ARGV[0] to pass browser name, but it thinks you're passing a file name. A workaround is to capture the value of ARGV[0] and then clear it before your test case runs:
browser = ARGV[0]
ARGV[0] = nil

Sinatra, Mongoid, Heroku, MongoHQ: connecting to Mongodb

Trying to get Mongoid up and running with Sinatra on Heroku (MongoHQ). Previous experience with Rails but first time with the stack and Sinatra.
Started with one of the simple examples on the web (app.rb):
require 'rubygems'
require 'sinatra'
require 'mongo'
require 'mongoid'
configure do
Mongoid.load!('mongoid.yml')
Mongoid.configure do |config|
if ENV['MONGOHQ_URL']
conn = Mongo::Connection.from_uri(ENV['MONGOHQ_URL'])
uri = URI.parse(ENV['MONGOHQ_URL'])
# problem happens here
config.master = conn.db(uri.path.gsub(/^\//, ''))
else
config.master = Mongo::Connection.from_uri("mongodb://localhost:27017").db('test')
end
end
end
# Models
class Counter
include Mongoid::Document
field :count, :type => Integer
def self.increment
c = first || new({:count => 0})
c.inc(:count, 1)
c.save
c.count
end
end
# Controllers
get '/' do
"Hello visitor n" + Counter.increment.to_s
end
For reference, mongoid.yml looks like:
development:
sessions:
default:
database: localhost
production:
sessions:
default:
uri: <%= ENV['MONGOHQ_URL'] %>
As per app.rb (# problem happens here), my logs say:
/app/app.rb:15:in `block (2 levels) in <top (required)>': undefined method `master=' for Mongoid::Config:Module (NoMethodError)
from /app/vendor/bundle/ruby/1.9.1/gems/mongoid-3.0.3/lib/mongoid.rb:112:in `configure'
from /app/app.rb:11:in `block in <top (required)>'
from /app/vendor/bundle/ruby/1.9.1/gems/sinatra-1.3.2/lib/sinatra/base.rb:1273:in `configure'
from /app/app.rb:8:in `<top (required)>'
I have also tried variants, including:
config.master = Mongo::Connection.from_uri(ENV['MONGOHQ_URL']).db('appXXXXX')
Mongoid.database = Mongo::Connection.from_uri(ENV['MONGOHQ_URL']).db('appXXXXXXX')
But get the same error:
undefined method `master` for Mongoid::Config:Module (NoMethodError)
or:
undefined method `database=` for Mongoid::Config:Module (NoMethodError)
What am I missing?
Shouldn't be
configure do
Mongoid.load!('mongoid.yml')
end
enough?
That's what the mongid docs are saying. The MONGOHQ_URL environment variable already contains every information to initialize the connection to the db.
So was using Mongoid 3.x ... which:
Doesn't use 10gen driver: uses Moped
Doesn't use config.master
The canonical sample code above which is all over the web works out of the box with Mongoid 2.x so have dropped back to that for the time being.
Thanks!

Resources