我如何获得RSpec的共享示例,例如Ruby Test :: Unit中的行为?

是否有类似于RSpec for test :: Unit测试中的shared_examples的插件/扩展名?

我能够使用以下代码实现共享测试(类似于RSpec共享示例):

module SharedTests def shared_test_for(test_name, &block) @@shared_tests ||= {} @@shared_tests[test_name] = block end def shared_test(test_name, scenario, *args) define_method "test_#{test_name}_for_#{scenario}" do instance_exec *args, &@@shared_tests[test_name] end end end 

要在Test :: Unit测试中定义和使用共享测试:

 class BookTest < ActiveSupport::TestCase extend SharedTests shared_test_for "validate_presence" do |attr_name| assert_false Books.new(valid_attrs.merge(attr_name => nil)).valid? end shared_test "validate_presence", 'foo', :foo shared_test "validate_presence", 'bar', :bar end 

如果您正在使用rails(或只是active_support),请使用Concern

 require 'active_support/concern' module SharedTests extend ActiveSupport::Concern included do # This way, test name can be a string :) test 'banana banana banana' do assert true end end end 

如果您没有使用active_support,只需使用Module#class_eval

这种技术建立在Andy H.的回答之上,他指出:

Test :: Unit测试只是Ruby类,因此您可以使用代码重用的[常规技术]

但是因为它可以使用ActiveSupport::Testing::Declarative#test它的优点是不会磨损你的下划线键:)

Test::Unit测试只是Ruby类,因此您可以使用与任何其他Ruby类相同的代码重用方法。

要编写共享示例,您可以使用模块。

 module SharedExamplesForAThing def test_a_thing_does_something ... end end class ThingTest < Test::Unit::TestCase include SharedExamplesForAThing end 
 require 'minitest/unit' require 'minitest/spec' require 'minitest/autorun' #shared tests in proc/lambda/-> basics = -> do describe 'other tests' do #override variables if necessary before do @var = false @var3 = true end it 'should still make sense' do @var.must_equal false @var2.must_equal true @var3.must_equal true end end end describe 'my tests' do before do @var = true @var2 = true end it "should make sense" do @var.must_equal true @var2.must_equal true end #call shared tests here basics.call end 

看看我几年前写的这个要点。 它仍然很好用: https : //gist.github.com/jodosha/1560208

 # adapter_test.rb require 'test_helper' shared_examples_for 'An Adapter' do describe '#read' do # ... end end 

像这样使用:

 # memory_test.rb require 'test_helper' describe Memory do it_behaves_like 'An Adapter' end