Run unit test with Ruby 2.0 and minitest 5.5 without Gemfile - ruby

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

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.

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?

Use test/unit with anonymous TestCase

This question belongs zu test-unit version 2.5.3
Problem solved with test-unit version 2.5.4
I have a test with many anonymous TestCases. It worked with test-unit 2.5.0, but the actual version 2.5.3 produces an error.
When I run this test:
gem 'test-unit', ">=2.5.2"
require 'test/unit'
Class.new( Test::Unit::TestCase ) do
def test_add
assert_equal( 2, 1+1)
end
end
no test is executed and I get the error undefined method sub' for nil:NilClass (NoMethodError) in testrunner.rb:361 (I use the actual test-unit-gem 2.5.3).
With a name for the TestCase, the problem disappears:
gem 'test-unit'
require 'test/unit'
X = Class.new( Test::Unit::TestCase ) do
def test_add
assert_equal( 2, 1+1)
end
end
In my real problem, I generate many TestCases. So I have a situation like:
gem 'test-unit'
require 'test/unit'
2.times {
X = Class.new( Test::Unit::TestCase ) do
def test_add
assert_equal( 2, 1+1)
end
end
}
If I execute this I get a warning already initialized constant X and the error:
comparison of Array with Array failed (ArgumentError) (in collector.rb:48:in sort_by').
My question(s):
How can I avoid the error?
Or: How can I create TestCases with dynamic assigned constants?
It seems this is down to a change in the latest version of the test-unit gem, which now requires a readable name for a class.
Something like this will work
gem 'test-unit', ">=2.5.2"
require 'test/unit'
Class.new( Test::Unit::TestCase ) do
def test_add
assert_equal( 2, 1+1)
end
def self.to_s
"GeneratedClass"
end
def self.name
to_s
end
end

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"

NoMethodError validate_presence_of using shoulda

Ok, I'm baffled. I'm trying to use shoulda with Test::Unit under Rails 3.1, having previously done so successfully with Rails 2.3.11.
I have the following in my Gemfile:
group :test do
gem 'shoulda'
end
(and I've run bundle install - bundle show shoulda shows c:/Ruby192/lib/ruby/gems/1.9.1/gems/shoulda-2.11.3)
I have the following test_helper.rb
ENV["RAILS_ENV"] = "test"
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require 'shoulda'
class ActiveSupport::TestCase
end
and the following user_test.rb
require 'test_helper'
class UserTest < ActiveSupport::TestCase
should validate_presence_of :email
should validate_format_of(:email).with("user+throwaway#subdom.example.com").with_message(/valid email address/)
should validate_presence_of(:encrypted_password)
should validate_confirmation_of :password
end
But when I do ruby -Itest test\unit\user_test.rb, I get the following error:
test/unit/user_test.rb:4:in `<class:UserTest>': undefined method `validate_presence_of' for UserTest:Class (NoMethodError)
What have I failed to set up properly?
Solved it. You need:
require 'shoulda/rails'
in test_helper.rb (not `require 'shoulda'); and the test case needs to be:
class Usertest < ActiveRecord::TestCase
(not < ActiveSupport::TestCase).
I'd tried both of those individually, but not together...

Resources