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

Sat*_*ish 8 ruby rspec testunit minitest

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

Jar*_*eck 5

如果您使用的是 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
Run Code Online (Sandbox Code Playgroud)

如果您不使用 active_support,只需使用Module#class_eval.

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

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

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


And*_*nes 1

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

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

module SharedExamplesForAThing
  def test_a_thing_does_something
    ...
  end
end

class ThingTest < Test::Unit::TestCase
  include SharedExamplesForAThing
end
Run Code Online (Sandbox Code Playgroud)