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

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.

Related

Ruby minitest LoadError

I was doing a tutorial on a Terminal and recommended to use gem minitest.
I followed an instruction but didn't run in the exact way.
works/ruby-book/test/rgb_test.rb
require 'minitest/ autorun'
require './lib/ rgb'
class RgbTest <Minitest:: Test
def test_ to_ hex
assert_ equal '#000000', to_ hex( 0, 0, 0)
end
end
works/ruby-book/lib/rgb.rb
def to_hex(r, g, b)
'#000000'
end
when I run $ ruby test/rgb_test.rb under ruby-book directory, I got
/Users/hostname/.rbenv/versions/2.4.0/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in`require': cannot load such file -- .lib/rgb (LoadError)
from/Users/hostname/.rbenv/versions/2.4.0/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in`require'
from test/rgb_test.rb:2:in `<main>'
What is happening here and how can I fix this problem?
My minitest version is 5.10.0.

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

ruby requiring an arbitrary ruby gem in irb session

I've been playing around with Rails for some time. But now I am attempting to build a ruby gem. And I am using rubymine which builds a gem template for you. In my case it looks like this:
$ ls
bin Gemfile lib Rakefile test
binarytree.gemspec Gemfile.lock LICENSE.txt README.md
merlino#johnmerlino:~/Documents/github/binarytree$
Inside the lib directory, I have a file called binarytree.rb, which contains the following contents:
require "binarytree/version"
module Binarytree
class BinaryNode
attr_accessor :value, :left, :right
def initialize(value=nil)
#value = value
#left = nil
#right = nil
end
def add(value)
if value <= #value
if #left
#left.add value
else
#left = BinaryNode.new value
end
else
if #right
#right.add value
else
#right = BinaryNode.new value
end
end
end
end
class BinaryTree
attr_accessor :root
def initialize
#root = nil
end
def add(value)
if !#root
#root = BinaryNode.new value
else
#root.add value
end
end
def contains(value)
node = #root
while node
if value == node.value
return true
elsif value < node.value
node = node.left
else
node = node.right
end
end
false
end
end
end
What I want to be able to do is run an irb (interactive ruby shell) session, and then be able to require 'binarytree' and have this code inside scope of irb, so I could start playing with it e.g. BinaryTree.new.
Right now I am not sure how to require this in irb:
require 'binarytree'
LoadError: cannot load such file -- binarytree
from /home/merlino/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:45:in require'
from /home/merlino/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:45:inrequire'
from (irb):1
from /home/merlino/.rvm/rubies/ruby-2.0.0-p0/bin/irb:13:in `'
I am on Ubuntu and I am using rvm to manage gems.
Any ideas?
You have two options:
Go into catalog of your gem and run require './lib/binarytree.rb'
Run rake install inside catalog of your gem - this will build and install this gem into system gems.
I got it working the following way:
1) You first need to edit the gemspec:
binarytree.gemspec
And edit the description and summary lines as so:
spec.description = "binary tree"
spec.summary = "binary tree summary"
Otherwise you will get the following error:
gem build doctor_toons.gemspec
ERROR: While executing gem ... (Gem::InvalidSpecificationException)
"FIXME" or "TODO" is not a description
2) Then run the gemspec as so:
gem build binarytree.gemspec
This should output something that looks like this:
binarytree-0.0.1.gem
3) Now if you are using rvm, make sure you are using the version you want, and run the following:
gem install ./binarytree-0.0.1.gem
The output should look something like this:
Successfully installed binarytree-0.0.1
Parsing documentation for binarytree-0.0.1
Installing ri documentation for binarytree-0.0.1
Done installing documentation for binarytree after 0 seconds
Done installing documentation for binarytree (0 sec).
1 gem installed
4) Then launch irb and require the new gem:
irb(main):001:0> require 'binarytree'

Cannot rescue NameError

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?

Verify version of a gem with bundler from inside Ruby

Is there a way to verify that I have the latest version of a gem from inside a Ruby program? That is, is there a way to do bundle outdated #{gemname} programmatically?
I tried looking at bundler's source code but I couldn't find a straight-forward way. Currently I'm doing this, which is fragile, slow and so inelegant:
IO.popen(%w{/usr/bin/env bundle outdated gemname}) do |proc|
output = proc.readlines.join("\n")
return output.include?("Your bundle is up to date!")
end
A way to avoid external execution:
For bundler 1.2.x
require 'bundler/cli'
# intercepting $stdout into a StringIO
old_stdout, $stdout = $stdout, StringIO.new
# running the same code run in the 'bundler outdated' utility
Bundler::CLI.new.outdated('rails')
# storing the output
output = $stdout.string
# restoring $stdout
$stdout = old_stdout
For bundler 1.3.x
require 'bundler/cli'
require 'bundler/friendly_errors'
# let's cheat the CLI class with fake exit method
module Bundler
class CLI
desc 'exit', 'fake exit' # this is required by Thor
def exit(*); end # simply do nothing
end
end
# intercepting $stdout into a StringIO
old_stdout, $stdout = $stdout, StringIO.new
# running the same code run in the 'bundler outdated' utility
Bundler.with_friendly_errors { Bundler::CLI.start(['outdated', 'rails']) }
# storing the output
output = $stdout.string
# restoring $stdout
$stdout = old_stdout
There is no programmatic way to use outdated command in bundler, because the code is in a Thor CLI file which prints output to the user. Bundler's tests are also issuing the command to the system and checking the output (Link to outdated tests).
It should be fairly simple to write your own method to mirror what the outdated method in cli.rb is doing, though. See the highlighted code here : Link to outdated method in Bundler source. Remove lines with Bundler.ui and return true/false based on the value of out_count
Update: I've extracted 'bundle outdated' into a reusable method without the console output and the exits. You can find the gist here : link to gist. I have tested this on bundler 1.3 and it seems to work.
bundle check list the gems that are out to date, you might want to use it.
Hmmm, sounds like you might want bundle show or gem env
Disappointing, this looks surprisingly difficult.
There are a couple of open issues in bundler where the official line appears to be:
At this point in time, there isn't a documented ruby API.
It's something that's on our list, though.
Looking through the bundler source code cli.rb, it's fairly clear that it's going to be tricky to call from ruby, or reproduce the code in a sensible manner.
Calling methods from CLI will be difficult because they're sprinkled with calls to exit.
Reproducing the code doesn't look fun either because there is quite a lot of bundler logic in there.
Good luck!
checking the source code of latest bundler source code
I could come up with this
https://github.com/carlhuda/bundler/blob/master/lib/bundler/cli.rb#L398
$ irb
1.9.3p327 :001 > require 'bundler'
=> true
1.9.3p327 :002 > def outdated_gems(gem_name,options={})
1.9.3p327 :003?> options[:source] ||= 'https://rubygems.org'
1.9.3p327 :004?> sources = Array(options[:source])
1.9.3p327 :005?> current_spec= Bundler.load.specs[gem_name].first
1.9.3p327 :006?> raise "not found in Gemfile" if current_spec.nil?
1.9.3p327 :007?> definition = Bundler.definition(:gems => [gem_name], :sources => sources)
1.9.3p327 :008?> options["local"] ? definition.resolve_with_cache! : definition.resolve_remotely!
1.9.3p327 :009?> active_spec = definition.index[gem_name].sort_by { |b| b.version }
1.9.3p327 :010?> if !current_spec.version.prerelease? && !options[:pre] && active_spec.size > 1
1.9.3p327 :011?> active_spec = active_spec.delete_if { |b| b.respond_to?(:version) && b.version.prerelease? }
1.9.3p327 :012?> end
1.9.3p327 :013?> active_spec = active_spec.last
1.9.3p327 :014?> raise "Error" if active_spec.nil?
1.9.3p327 :015?> outdated = Gem::Version.new(active_spec.version) > Gem::Version.new(current_spec.version)
1.9.3p327 :016?> {:outdated=>outdated,:current_spec_version=>current_spec.version.to_s,:latest_version=>active_spec.version.to_s}
1.9.3p327 :017?> end
=> nil
1.9.3p327 :018 >
1.9.3p327 :019 >
1.9.3p327 :020 >
1.9.3p327 :021 >
1.9.3p327 :022 > outdated_gems('rake')
=> {:outdated=>true, :current_spec_version=>"10.0.3", :latest_version=>"10.0.4"}
This may not work with earlier version of bundler.

Resources