8

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

4

5 回答 5

6

如果您使用的是 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它的优点是不会磨损你的下划线键:)

于 2014-12-29T04:53:52.960 回答
2

我能够使用以下代码实现共享测试(类似于 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
于 2013-02-08T22:19:47.920 回答
1

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

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

module SharedExamplesForAThing
  def test_a_thing_does_something
    ...
  end
end

class ThingTest < Test::Unit::TestCase
  include SharedExamplesForAThing
end
于 2013-01-24T17:27:32.520 回答
0

看看我几年前写的这个要点。它仍然很好用: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
于 2014-04-09T07:47:28.100 回答
0
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
于 2013-06-06T19:36:55.687 回答