Use test/unit with anonymous TestCase - ruby

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

Related

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

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...

Ruby test unit: uninitialized constant Test::Unit::UnitCase

I am trying to run this test, but I am running int a problem. Every time that I attempt to run the test, I am getting the following error:
uninitialized constant Test::Unit::UnitCase
I am running it on Windows 7, ruby 186.
Path points to C:\ruby186\bin
Ruby Bin C:\ruby186\bin
This is not a rails app. This is just ruby.
This is the code:
require 'rubygems'
require 'test/unit'
require 'shoulda'
require './AngryBadger'
class AngryBadger < Test::Unit::UnitCase
def setup
test_uri = ""
#ab = AngryBadger.new()
end
should "have no fear" do
assert(true)
end
end
I suspect that this can be fixed through configuration, but I don't know what I could do.
You should be subclassing from Test::Unit::TestCase instead:
class AngryBadger < Test::Unit::TestCase

Why doesn't relative_require work on Ruby 1.8.6?

I'm learning Ruby (using version 1.8.6) on Windows 7.
When I try to run the stock_stats.rb program below, I get the following error:
C:\Users\Will\Desktop\ruby>ruby stock_stats.rb
stock_stats.rb:1: undefined method `require_relative' for main:Object (NoMethodE
rror)
I have three v.small code files:
stock_stats.rb
require_relative 'csv_reader'
reader = CsvReader.new
ARGV.each do |csv_file_name|
STDERR.puts "Processing #{csv_file_name}"
reader.read_in_csv_data(csv_file_name)
end
puts "Total value = #{reader.total_value_in_stock}"
csv_reader.rb
require 'csv'
require_relative 'book_in_stock'
class CsvReader
def initialize
#books_in_stock = []
end
def read_in_csv_data(csv_file_name)
CSV.foreach(csv_file_name, headers: true) do |row|
#books_in_stock << BookInStock.new(row["ISBN"], row["Amount"])
end
end
# later we'll see how to use inject to sum a collection
def total_value_in_stock
sum = 0.0
#books_in_stock.each {|book| sum += book.price}
sum
end
def number_of_each_isbn
# ...
end
end
book_in_stock.rb
require 'csv'
require_relative 'book_in_stock'
class CsvReader
def initialize
#books_in_stock = []
end
def read_in_csv_data(csv_file_name)
CSV.foreach(csv_file_name, headers: true) do |row|
#books_in_stock << BookInStock.new(row["ISBN"], row["Amount"])
end
end
# later we'll see how to use inject to sum a collection
def total_value_in_stock
sum = 0.0
#books_in_stock.each {|book| sum += book.price}
sum
end
def number_of_each_isbn
# ...
end
end
Thanks in advance for any help.
require_relative doesn't exist in your version of Ruby. You could upgrade Ruby, install the backports gem and require 'backports/1.9.1/kernel/require/relative' but the easiest fix will be to change your require to:
require File.join(File.dirname(__FILE__), 'csv_reader')
Edit:
Back in the days where this question was asked it referred to Ruby 1.8.6 where there was no require_relative. By now Ruby 1.8.6 is outdated and shouldn't be used anymore.
Original:
There is simply no method name require_relative. You can use require there aswell.
The require_relative function is included in an extension project to the Ruby core libraries, found here: http://www.rubyforge.org/projects/extensions
You should be able to install them with gem install extensions.
Then in your code add the following line before the require_relative:
require 'extensions/all'

Webrat Mechanize outside of Rails

I'm trying to use Webrat in a standalone script to automate some web browsing. How do I get the assert_contain method to work?
require 'rubygems'
require 'webrat'
include Webrat::Methods
include Webrat::Matchers
Webrat.configure do |config|
config.mode = :mechanize
end
visit 'http://gmail.com'
assert_contain 'Welcome to Gmail'
I get this error
/usr/lib/ruby/gems/1.8/gems/webrat-0.6.0/lib/webrat/core/matchers/have_content.rb:57:in 'assert_contain': undefined method assert' for #<Object:0xb7e01958> (NoMethodError)
assert_contain and other assertions are methods of test/unit, try to require it and use webrat from inside a test method:
require 'test/unit'
class TC_MyTest < Test::Unit::TestCase
def test_fail
assert(false, 'Assertion was false.')
end
end
anyway i haven't tested it but I have a working spec_helper for rspec if this can interest you:
require File.dirname(__FILE__) + "/../config/environment" unless defined?(RAILS_ROOT)
require 'spec/rails'
require "webrat"
Webrat.configure do |config|
config.mode = :rails
end
module Spec::Rails::Example
class IntegrationExampleGroup < ActionController::IntegrationTest
def initialize(defined_description, options={}, &implementation)
defined_description.instance_eval do
def to_s
self
end
end
super(defined_description)
end
Spec::Example::ExampleGroupFactory.register(:integration, self)
end
end
plus a spec:
# remember to require the spec helper
describe "Your Context" do
it "should GET /url" do
visit "/url"
body.should =~ /some text/
end
end
give it a try I found it very useful (more than cucumber and the other vegetables around) when there is no need to Text specs (features) instead of Code specs, that I like the most.
ps you need the rspec gem and it installs the 'spec' command to execute your specs.

Resources