Cannot rescue NameError - ruby

Can someone tell me what I am doing wrong here, please?
wtf.rb
require 'minitest/autorun'
class MyPlugin
def self.valid_plugin?(plugin_class)
begin
plugin_class.ancestors.include?(self)
rescue NameError
false
end
end
end
class MyPluginTest < Minitest::Test
def test_valid_plugin_handles_missing_constant
assert_equal false, MyPlugin.valid_plugin?(MyMissingConstant)
end
end
Environment
$ ruby -v
ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-darwin13.0]
$ gem list --local
*** LOCAL GEMS ***
bigdecimal (1.2.4)
bundler (1.7.3)
io-console (0.4.2)
json (1.8.1)
minitest (5.4.2, 4.7.5)
psych (2.0.5)
rake (10.1.0)
rdoc (4.1.0)
test-unit (2.1.2.0)
$ ruby wtf.rb
Run options: --seed 32486
# Running:
E
Finished in 0.001228s, 814.3322 runs/s, 0.0000 assertions/s.
1) Error:
MyPluginTest#test_valid_plugin_handles_missing_constant:
NameError: uninitialized constant MyPluginTest::MyMissingConstant
wtf.rb:15:in `test_valid_plugin_handles_missing_constant'
1 runs, 0 assertions, 0 failures, 1 errors, 0 skips

MyMissingConstant is evaluated before the valid_plugin? method is called. You have to either rescue at the call site, or pass a string and look up the constant within your method.
Kernel.const_get is probably the simplest way to do that. For more detail, look at question slike this one:
How to convert a string to a constant in Ruby?

Related

The term 'RSpec' is not recognized as the name of a cmdlet, function, script file, error

I'm trying to test ruby file using rspec. But I'm getting error and It says
rspec : The term 'rspec' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a
path was included, verify that the path is correct and try again.
At line:1 char:1
+ rspec test2.rb
+ ~~~~~
+ CategoryInfo : ObjectNotFound: (rspec:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
](https://i.stack.imgur.com/axHV5.png)
How can I fix this.
Here I attached my all 3 ruby files also
user.rb
require_relative 'main'
print 'Input array: '
solution = Solution.new(gets.split.map(&:to_f))
if solution.posled?
puts "Yes, posled: #{solution.arr_new}"
else
puts 'No'
end
main.rb
# This class is responsible for checking is the elements before first negative sorted from min to max.
class Solution
attr_accessor :arr_new, :arr
def initialize(arr)
#arr = arr
#arr_new = []
#was_negative = false
#arr.each_with_index do |value, _index|
if value.negative?
#was_negative = true
break
else
#arr_new.push(value)
end
end
end
def posled?(arr_new = #arr_new)
if arr_new.any? && #was_negative
arr_new == arr_new.sort
else
false
end
end
end
test2.rb
require_relative 'main2'
RSpec.describe Solution do
describe '#Solution' do
it 'should return true' do
expect(Solution.posled?([1, 2, 3])).to eq(false)
end
it 'should return true if contains posled before negative el' do
uncorrect = [1, 2, 3, -1]
Random.rand(10).times { uncorrect.push(Random.rand(-10..9)) }
expect(Solution.posled?(uncorrect)).to eq(true)
end
it 'should return false if there is no posled before first neg el' do
uncorrect = [1, 3, 2, -1]
Random.rand(10).times { uncorrect.push(Random.rand(-10..9)) }
expect(Solution.posled?(uncorrect)).to eq(false)
end
it 'should return false if first el negative' do
uncorrect = [-1, 1, 2, 3]
Random.rand(10).times { uncorrect.push(Random.rand(-10..9)) }
expect(Solution.posled?(uncorrect)).to eq(false)
end
it 'should return false if there is no negative elements' do
uncorrect = [1, 2, 3]
Random.rand(10).times { uncorrect.push(Random.rand(-10..9)) }
expect(Solution.posled?(uncorrect)).to eq(false)
end
end
end
I tried ruby test file and looking for get errors and corrections. But when I run rspec I'm getting an error. How can I fix this
Your problem has nothing to do with the ruby files, according to your first output the command is not found.
There might be different reasons for this. Can you run ruby -version either in cmd or powershell? If it works, than you should check if rspec is installed within your ruby instance. Run gem list rspec the output should be like this:
*** LOCAL GEMS ***
rspec (3.12.0)
rspec-core (3.12.0)
rspec-expectations (3.12.0)
rspec-mocks (3.12.0)
rspec-support (3.12.0)
If it is found try reinstalling it with gem uninstall rspec and than gem install rspec.
In case neither ruby nor rspec work, you should check you PATH variable with echo %PATH% in cmd or $Env:Path in Powershell. There should be a record pointing to ruby bin folder.
The other thing to keep in mind is you may have multiple ruby versions installed. RubyInstaller website suggests using uru. If you've installed ruby with uru, you first need to activate your ruby instance. Either in Powershell or cmd run uru ls to see all the versions installed. In my case:
187p374 : ruby 1.8.7 (2013-06-27 patchlevel 374) [i386-mingw32]
233p222 : ruby 2.3.3p222 (2016-11-21 revision 56859) [x64-mingw32]
253p105 : ruby 2.5.3p105 (2018-10-18 revision 65156) [x64-mingw32]
268p205 : ruby 2.6.8p205 (2021-07-07 revision 67951) [x64-mingw32]
274p191 : ruby 2.7.4p191 (2021-07-07 revision a21a3b7d23) [x64-mingw32]
310p0 : ruby 3.1.0p0 (2021-12-25 revision fb4df44d16) [i386-mingw32]
jruby : jruby 9.2.19.0 (2.5.8) 2021-06-15 55810c552b Java HotSpot(TM) 64...
main : ruby 3.0.2p107 (2021-07-07 revision 0db68f0233) [x64-mingw32]
You have to select one of the listed versions, e.g. uru main, than all the ruby commands and installed gems should work for the opened Powershell or cmd session, path output will also feature the selected version.
In case you have some other software to manage multiple ruby versions please refer to its documentation.

`require': cannot load such file -- curses (LoadError)

I am a ruby beginner and trying to understand and learn ruby. I came across this error while trying to run a ruby file which uses "require curses" but I am getting the following error while doing so. Any help or hint is appreciated.
desktop$ ruby curses.rb
/desktop/jsipp-master$ gem list
*** LOCAL GEMS ***
bigdecimal (1.2.8)
CFPropertyList (2.2.8)
curses (1.2.4)
did_you_mean (1.0.0)
enumerate (0.0.7)
enumerated (1.0.1)
enumeration (1.3.3)
ffi (1.9.25)
ffi-rzmq (2.0.6)
ffi-rzmq-core (1.0.6)
io-console (0.4.5)
json (1.8.3)
libxml-ruby (2.9.0)
minitest (5.8.5)
net-telnet (0.1.1)
nokogiri (1.5.6)
power_assert (0.2.6)
psych (2.1.0)
rake (10.4.2)
rdoc (4.2.1)
sqlite3 (1.3.11)
test-unit (3.1.5)
/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- curses (LoadError)
from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from curses.rb:3:in `<main>'
jsipp-master$ ruby -v
ruby 2.3.3p222 (2016-11-21 revision 56859) [universal.x86_64-darwin17]
#!/usr/bin/ruby
require 'curses'
require 'ffi-rzmq'
require 'enumerator'
POSITIONS = "%15s %8s %8s %12s %12s %12s\n"
POSITIONS2 = "%-38s %-38s\n"
POSITIONS3 = "%15s %-12s%%-10s%%-10s%%-10s%%-15s\n"
OUT_ARROW = "-------->"
IN_ARROW = "<--------"
PAUSE = "[%6dms]"
class MinuteLongBuffer
def initialize
#values = []
end
def add v
#values << [Time.new.to_f, v]
end
def count
#values = #values.keep_if {|v| v[0] > (Time.new.to_f - 1)}
#values.length
end
end
class Scenario
def parse_scenario_desc desc
#strings = []
#msg_counts = []
parts = desc.split(";")
parts.each do |part|
type, value = part.split(":")
if type == "IN"
#strings << (POSITIONS3 % [value, IN_ARROW])
elsif type == "OUT"
#strings << (POSITIONS3 % [value, OUT_ARROW])
elsif type == "PAUSE"
#strings << (POSITIONS3 % [(PAUSE % value), ""])
end
#msg_counts << 0
#unexpected_msg_counts << 0
#timeout_counts << 0
end
end
def inc_msg idx
#msg_counts[idx.to_i] += 1
if idx.to_i == 0
#new_calls.add 1
end
end
def inc_unexpected idx
#unexpected_msg_counts[idx.to_i] += 1
end
def inc_timeout idx
#timeout_counts[idx.to_i] += 1
end
def update
Curses.clear
Curses.addstr(POSITIONS % ["Call-rate", "Length", "Port", "Total-time", "Total-calls", "Remote-host"])
Curses.addstr(POSITIONS % [("?cps"), "? ms", "????", ("%.2fs" % (Time.new.to_f - #start)), "?", "??? (???)"])
Curses.addstr("\n")
Curses.addstr(POSITIONS2 % ["%d new calls during 1.000s period" % #new_calls.count, "?ms scheduler resolution"])
Curses.addstr(POSITIONS2 % ["? concurrent calls (limit ?)", "Peak was ? calls, after ?s"])
Curses.addstr(POSITIONS2 % ["? out-of-call msg (discarded)", "? open sockets"])
Curses.addstr("\n")
Curses.addstr((POSITIONS3 % ["", "",]) % ["Messages", "Retrans", "Timeout", "Unexpected-Msg"])
#strings.each_with_index do |s, i|
Curses.addstr(s % [#msg_counts[i], 0, #timeout_counts[i], #unexpected_msg_counts[i]])
end
Curses.refresh
end
def initialize
#new_calls = MinuteLongBuffer.new
#strings = []
#msg_counts = []
#unexpected_msg_counts = []
#timeout_counts = []
#start = Time.new.to_f
Thread.new do
context = ZMQ::Context.new
socket = context.socket(ZMQ::SUB)
socket.connect("tcp://localhost:5556")
socket.setsockopt(ZMQ::SUBSCRIBE, "SIPP")
socket2 = context.socket(ZMQ::REQ)
socket2.connect("tcp://localhost:5557")
socket2.send_string "",0
socket2.recv_string msg2 = ""
parse_scenario_desc msg2
loop do
socket.recv_strings(msgs = [])
msgs.each do |msg|
name, ts, scenario, callnum, callid, idx, result = msg.split(":")
if name == "SIPP-PHASE_SUCCESS"
inc_msg idx
end
if name == "SIPP-UNEXPECTED_MSG_RECVD"
inc_unexpected idx
end
if name == "SIPP-RECV_TIMED_OUT"
inc_timeout idx
end
end
end
end
end
end
SCENARIO = Scenario.new
Curses.init_screen()
Thread.new do
loop do
tmp = Curses.getch
end
end
loop do
SCENARIO.update
sleep 1
end
Also when I check the ruby version it is pointing to 2.3.3 but while running the it shows me ruby 2.3.0 running the file. If someone could explain why is that would also help me.
After installing gems in file manually I am getting another error please see below.
/jsipp-master$ ruby curses.rb
Unable to load this gem. The libzmq library (or DLL) could not be found.
If this is a Windows platform, make sure libzmq.dll is on the PATH.
If the DLL was built with mingw, make sure the other two dependent DLLs,
libgcc_s_sjlj-1.dll and libstdc++6.dll, are also on the PATH.
For non-Windows platforms, make sure libzmq is located in this search path:
["/Library/Ruby/Gems/2.3.0/gems/ffi-rzmq-core-1.0.6/lib/ffi-rzmq-core/../../ext/libzmq.dylib", "/usr/local/bin/libzmq.dylib", "/usr/bin/libzmq.dylib", "/bin/libzmq.dylib", "/usr/sbin/libzmq.dylib", "/sbin/libzmq.dylib", "/opt/X11/bin/libzmq.dylib", "/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/libzmq.dylib", "/usr/local/lib/libzmq.dylib", "/opt/local/lib/libzmq.dylib", "/usr/local/lib/libzmq.dylib", "/usr/lib64/libzmq.dylib"]
/Library/Ruby/Gems/2.3.0/gems/ffi-rzmq-core-1.0.6/lib/ffi-rzmq-core/libzmq.rb:61:in `rescue in <module:LibZMQ>': The libzmq library (or DLL) could not be loaded (LoadError)
from /Library/Ruby/Gems/2.3.0/gems/ffi-rzmq-core-1.0.6/lib/ffi-rzmq-core/libzmq.rb:10:in `<module:LibZMQ>'
from /Library/Ruby/Gems/2.3.0/gems/ffi-rzmq-core-1.0.6/lib/ffi-rzmq-core/libzmq.rb:7:in `<top (required)>'
from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /Library/Ruby/Gems/2.3.0/gems/ffi-rzmq-core-1.0.6/lib/ffi-rzmq-core.rb:3:in `<top (required)>'
from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /Library/Ruby/Gems/2.3.0/gems/ffi-rzmq-2.0.6/lib/ffi-rzmq.rb:66:in `<top (required)>'
from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:127:in `require'
from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:127:in `rescue in require'
from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:40:in `require'
from curses.rb:4:in `<main>'
It is possible you have not installed the curses gem.
You can check to see if it is installed using the gem list command. If your gem is not listed, it isn't installed:
$ gem list curses
*** LOCAL GEMS ***
$
If it is not installed, install the gem using the gem install command:
$ gem install curses
Fetching: curses-1.2.4.gem (100%)
Building native extensions. This could take a while...
Successfully installed curses-1.2.4
Parsing documentation for curses-1.2.4
Installing ri documentation for curses-1.2.4
Done installing documentation for curses after 0 seconds
1 gem installed
$
You can read more in the online gem command reference.
That should get you beyond the error you are seeing.

Run unit test with Ruby 2.0 and minitest 5.5 without Gemfile

I was learning Ruby by reading Programming Ruby and there is this example code:
require_relative 'count_frequency'
require_relative 'words_from_string'
require 'test/unit'
class TestWordsFromString < Test::Unit::TestCase
def test_empty_string
assert_equal([], words_from_string(''))
assert_equal [], words_from_string(' ')
end
def test_single_word
assert_equal ['cat'], words_from_string('cat')
assert_equal ['cat'], words_from_string(' cat ')
end
def test_many_words
assert_equal ['the', 'cat', 'sat', 'on', 'the', 'cat'], words_from_string('the cat sat on the mat')
end
def test_ignore_punctuation
assert_equal ['the', "cat's", 'mat'], words_from_string("the cat's mat")
end
end
When I tried to run it, an error occured:
MiniTest::Unit::TestCase is now Minitest::Test.
More detailed error message:
I'm using ruby 2.0.0p481 (2014-05-08 revision 45883) [universal.x86_64-darwin14] and minitest (5.5.0, 5.4.3, 5.3.5, 4.3.2). I did some search and found that since minitest5.0, MiniTest::Unit::TestCase has changed to Minitest::Test. But I cannot do anything since it's in the source file of the gem. Some suggests that require minitest 4.** in Gemfile, but i'm just running a few scripts. There is no need for Gemfile I suppose. And I certainly don't want to uninstalling minitest5.**. So is there a way I could run this script with minitest5.5 and ruby 2.0?
The tests should still run. I have the same set up and even though I get that error, the tests are executed.
→ ruby --verbose etl_test.rb
MiniTest::Unit::TestCase is now Minitest::Test. From etl_test.rb:4:in `<main>'
Run options: --seed 61653
# Running:
....
Finished in 0.001316s, 3039.5137 runs/s, 3039.5137 assertions/s.
4 runs, 4 assertions, 0 failures, 0 errors, 0 skips
classyhacker:~/dev/github/exercism/ruby/etl
→ rbenv versions
system
1.9.3-p448
2.0.0-p451
2.1.0
2.1.1
2.1.2
* 2.1.3 (set by RBENV_VERSION environment variable)
jruby-1.7.8
classyhacker:~/dev/github/exercism/ruby/etl
→ gem list | grep minitest
minitest (5.5.1, 5.4.3, 4.7.5)
My test looks like
require 'minitest/autorun'
require_relative 'etl'
class TransformTest < MiniTest::Unit::TestCase
def test_transform_one_value
old = { 1 => ['A'] }
expected = { 'a' => 1 }
assert_equal expected, ETL.transform(old)
end
require minitest/autorun is also the suggested way in rubydoc http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest/rdoc/MiniTest.html

Verify not working in Ruby with Selenium::WebDriver

I am just starting to figure how to create unit tests using "test/unit". I copied the code generated by Selenium IDE and paste it into my Ruby test method.
But when running it with Ruby.exe, for some reason it is throwing an error:
Finished tests in 31.835891s, 0.0314 tests/s, 0.0942 assertions/s.
1) Error:
test_method(MyTestClass):
NameError: uninitialized constant Test::Unit::AssertionFailedError
teste-noticia.rb:30:in `rescue in verify'
teste-noticia.rb:29:in `verify'
teste-noticia.rb:42:in `test_method'
1 tests, 3 assertions, 0 failures, 1 errors, 0 skips
Anyone could help me to how assert correctly desired strings? Any good practice is welcome ;-).
Here is the code:
# encoding: utf-8
require "selenium-webdriver"
require "test/unit"
class MyTestClass < Test::Unit::TestCase
def setup
#driver = Selenium::WebDriver.for :firefox
#base_url = "http://www.yoursite.com"
#driver.manage.timeouts.implicit_wait = 30
#verification_errors = []
#wait = Selenium::WebDriver::Wait.new :timeout => 10
end
def teardown
#driver.quit
assert_equal [], #verification_errors
end
def element_present?(how, what)
#driver.find_element(how, what)
true
rescue Selenium::WebDriver::Error::NoSuchElementError
false
end
def verify(&blk)
yield
rescue Test::Unit::AssertionFailedError => ex
#verification_errors << ex
end
#your test methods go here
def test_method
#driver.get(#base_url + "/my-desired-path")
verify { assert_equal "Obama wins and will move U.S. forward", #driver.find_element(:css, "h1").text }
end
end
EDIT
My local gems:
C:\Users\wmj>gem list
*** LOCAL GEMS ***
addressable (2.3.2)
bigdecimal (1.1.0)
childprocess (0.3.6)
ffi (1.1.5 x86-mingw32)
io-console (0.3)
json (1.5.4)
libwebsocket (0.1.5)
minitest (2.5.1)
multi_json (1.3.7)
rake (0.9.2.2)
rdoc (3.9.4)
rubyzip (0.9.9)
selenium-webdriver (2.26.0)
test-unit (2.5.2)
I believe the issue is that you have required the 'minitest' gem, but are trying to use the classes in the 'test-unit' gem. 'Minitest' is installed by default in Ruby 1.9 instead of 'Test-Unit' (which was installed by default in 1.8). Minitest is only partially backwards compatible with Test-Unit.
Possible solutions:
Switch to Minitest:
It is the Test::Unit::AssertionFailedError in the verify method that is causing the exception. You could change it to the minitest equivalent, which appears to be MiniTest::Assertion. So your verify method would become:
def verify(&blk)
yield
rescue MiniTest::Assertion => ex
#verification_errors << ex
end
Use Test-Unit instead of Minitest:
Assuming you have the test-unit gem already installed (gem install test-unit), manually specify that you want to use that gem when doing require 'test/unit':
gem "test-unit"
require "test/unit"

Rspec2 issue with Rcov

In my Rakefile, I have a task defined like this:
namespace :test do
desc "Run all specs."
RSpec::Core::RakeTask.new(:spec) do |t|
t.pattern = 'spec/**/*_spec.rb'
t.verbose = false
end
RSpec::Core::RakeTask.new(:coverage) do |t|
t.rcov = true
t.rcov_opts = %q[--exclude "spec"]
t.verbose = true
end
end
When running test:coverage, I get this:
./spec/foo_spec.rb:3: undefined method `describe' for main:Object (NoMethodError)
from /Library/Ruby/Gems/1.8/gems/rcov-0.9.9/bin/rcov:516:in `load'
from /Library/Ruby/Gems/1.8/gems/rcov-0.9.9/bin/rcov:516
from /usr/bin/rcov:19:in `load'
from /usr/bin/rcov:19
rake aborted!
ruby -S rcov -Ispec:lib --exclude "spec" "./spec/foo_spec.rb" failed
Below my gem list:
diff-lcs (1.1.2)
rake (0.8.7)
rcov (0.9.9)
rspec (2.3.0)
rspec-core (2.3.1)
rspec-expectations (2.3.0)
rspec-mocks (2.3.0)
Any idea? Thanks in advance.
The solution, from David Chelimsky:
http://rubyforge.org/pipermail/rspec-users/2010-December/019077.html
require "rspec"
Cheers.

Resources