方法1: -
test.rb
class Test < Test::Unit::TestCase
def test_sample
assert_true(test)
assert_equal(a,b)
end
end
结果: - 完成时间为38.329532529秒。
1 tests, 2 assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications
100% passed
方法2: -
test.rb
class Test < Test::Unit::TestCase
require 'helper'
include AssertionHelper
def test_sample
test_assertion
end
end
helper.rb
include Test::Unit::Assertions
module AssertionHelper
def test_assertion
assert_true(test)
assert_equal(a,b)
end
end
结果: -
Finished in 38.329532529 seconds.
1 tests, 2 assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications
100% passed
方法3: -
test.rb
class Test < Test::Unit::TestCase
require 'helper'
def test_sample
AssertionHelper.test_assertion()
end
end
helper.rb
include Test::Unit::Assertions
module AssertionHelper
def self.test_assertion
assert_true(test)
assert_equal(a,b)
end
end
结果: -
Finished in 38.329532529 seconds.
1 tests, 0 assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications
100% passed
当使用方法3时,我得到断言计数为&#34; 0&#34;而不是&#34; 2&#34;。
我可以使用方法2将断言计数设为2吗?
答案 0 :(得分:1)
您可以将当前的TestCase
传递给您的模块,如下所示:
sample_test.rb:
require 'test-unit'
require 'helper'
def a; true ; end
def b; true ; end
def test; true ; end
class SampleTest < Test::Unit::TestCase
def test_sample
AssertionHelper.my_assertion(self)
end
end
helper.rb:
module AssertionHelper
def self.my_assertion(test_case)
test_case.instance_exec do
assert_true(test)
assert_equal(a, b)
end
end
end
答案 1 :(得分:0)
很抱歉,但我无法重现您的情况,请提供Test::Unit
版本和您的红宝石版本?最重要的是你的Gemfile与Gemfile.lock。以下设置适用于我(我使用ruby 2.2.0和测试单元3.0.8):
ruby-2.2.0 in ~/projects/test-unit ♥ tree
.
├── Gemfile
├── Gemfile.lock
└── test
├── helper.rb
└── sample_test.rb
1 directory, 4 files
ruby-2.2.0 in ~/projects/test-unit ♥ cat Gemfile
# A sample Gemfile
source "https://rubygems.org"
# gem "rails"
gem 'test-unit', '~> 3.0.8'
ruby-2.2.0 in ~/projects/test-unit ♥ cat Gemfile.lock
GEM
remote: https://rubygems.org/
specs:
power_assert (0.2.2)
test-unit (3.0.8)
power_assert
PLATFORMS
ruby
DEPENDENCIES
test-unit (~> 3.0.8)
sample_test.rb:
require 'test-unit'
def a; true ; end
def b; true ; end
def test; true ; end
class SampleTest < Test::Unit::TestCase
require 'helper'
include AssertionHelper
def test_sample
my_assertion
end
end
helper.rb:
module AssertionHelper
def my_assertion
assert_true(test)
assert_equal(a, b)
end
end
正如预期的那样,运行testrb
会产生2个断言。
ruby-2.2.0 in ~/projects/test-unit ♥ testrb
Loaded suite .
Started
.
Finished in 0.000828 seconds.
1 tests, 2 assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications
100% passed
1207.73 tests/s, 2415.46 assertions/s
ruby-2.2.0 in ~/projects/test-unit ♥
UPDATE :这实际上很奇怪你没有得到任何错误(在你的方法3上),因为我得到了这个:NoMethodError: undefined method 'assert_true' for AssertionHelper:Module
这是真的,因为{{1没有实现任何其他方法,您不能在其上运行任何AssertionHelper
方法。只需使用我上面的代码(你的方法2),你应该没事。如果你仍然好奇可以做些什么,看看Test::Unit::Assertions,还有很多内置的断言定义,也许你觉得有用。
或者,更好的是,使用MiniTest或RSpec,因为Test :: Unit is deprecated并且只留在标准库中用于传统测试套件。